1. 程式人生 > >6月8日

6月8日

linux

12.10 Nginx訪問日誌

Nginx訪問日誌

1. 進入配置文件

vim /usr/local/nginx/conf/nginx.conf //搜索log_format

更改以下配置

log_format aming '$remote_addr $http_x_forwarded_for [$time_local]'

如下圖:

技術分享圖片

日誌格式字段含義如下:

combined_realip為日誌格式的名字,後面可以調用它。

技術分享圖片

2.虛擬主機配置文件中指定訪問日誌的路徑

vim /usr/local/nginx/conf/vhost/test.com.conf

增加如下內容:(這裏的combined_realip就是nginx.conf中定義的日誌格式名字

access_log /tmp/test.com.log combined_realip;

技術分享圖片

3.測試語法及重新加載配置

/usr/local/nginx/sbin/nginx -t

/usr/local/nginx/sbin/nginx -s reload

4.使用curl測試

curl -x127.0.0.1:80 test.com -I

技術分享圖片

curl -x127.0.0.1:80 test2.com/admin -I

技術分享圖片

curl -x127.0.0.1:80 test2.com/admin/index.html -I

技術分享圖片

4.1查看一下日誌

cat /tmp/test.com.log

技術分享圖片

12.11 Nginx日誌切割

Nginx日誌切割

1.自定義一個

shell腳本

vim /usr/local/sbin/nginx_log_rotate.sh

定義如下內容:

#!/bin/bash ## 假設nginx的日誌存放路徑為/data/logs/ d=`date -d "-1 day" +%Y%m%d` //這個日期是昨天的日期,因為日誌切割是第二天才執行這個腳本的。 logdir="/data/logs" nginx_pid="/usr/local/nginx/logs/nginx.pid" cd $logdir for log in `ls *.log` do mv $log $log-$d done /bin/kill -HUP `cat $nginx_pid` //

Nginx-s重新加載配置文件一樣

技術分享圖片

2.執行腳本

sh執行,-x是顯示執行的過程(可視化)

sh -x /usr/local/sbin/nginx_log_rotate.sh

技術分享圖片

2.1查看一下/data/logs目錄

ls /data/logs

3.添加任務計劃 (腳本之後還要加一個任務計劃)

crontab -e //添加任務計劃

增加如下內容:(每天淩晨0執行一下這個腳本)

0 0 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh

技術分享圖片

3.1 定期刪除日誌:

find /tmp/ -name *.log-* -type f -mtime +30 |xargs rm

(找出30天前名字為log-*後綴的日誌並刪除)



12.12 靜態文件不記錄日誌和過期時間

靜態文件不記錄日誌和過期時間

1.修改虛擬主機配置文件

添加以下配置:

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ //匹配脫義靜態文件 { expires 7d; //配置過期時間 access_log off; } location ~ .*\.(js|css)$ //匹配js,css文件 { expires 12h; access_log off; }

技術分享圖片

2.測試語法及重新加載配置

/usr/local/nginx/sbin/nginx -t

/usr/local/nginx/sbin/nginx -s reload

3.使用curl測試靜態文件不記錄,進入目錄並創建1.gif 2.js 後綴的文件

cd /data/wwwroot/test.com

vim 1.gif //內容123 ABC

vim 2.js //內容abc abc abc

技術分享圖片

3.1 curl看一下狀態結果並查看日誌確認(gif和js的沒有日誌記錄)

技術分享圖片

4.測試一下過期時間

curl一下,因為之前有定義過期expires 12h,所以狀態中有這個max-age

curl -x127.0.0.1:80 test.com/2.js -I

技術分享圖片

4.1 我們再去修改一下腳本文件試著把過期時間去掉讓其不生效

vim /usr/local/nginx/conf/vhost/test.com.conf

將定義js模塊的 expires 12h 註釋掉

技術分享圖片

4.2 測試語法及重新加載配置

/usr/local/nginx/sbin/nginx -t

/usr/local/nginx/sbin/nginx -s reload

4.3 curl測試查看一下狀態

curl -x127.0.0.1:80 test.com/2.js -I

技術分享圖片



6月8日