12.10 通路日志
Nginx日志格式:
[root@centos-01linux ~]# vim /usr/local/nginx/conf/nginx.conf
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
' $host "$request_uri" $status'
' "$http_referer" "$http_useragent"';
說明:
“combined realip”:日志格式名稱;'$remote addr $http x forwarded for [$time_ local]' ' $host "$requesturi" $status' ' "$http referer" "$http user agent"' :日志内容。
注釋:
名稱 含義
$remote_addr 用戶端IP(公網IP)
$http_x_forwarded_for 代理伺服器的IP
$time_local 伺服器本地時間
$host 通路主機名(域名)
$request_uri 通路的URL位址
$status 狀态碼
$http_referer referer
$http_user_agent user_agent
定義虛拟主機日志格式
定義虛拟主機的前提是在Nginx配置檔案中設定日志格式,然後才能在虛拟主機中進行調用(格式名稱)。
[root@centos-01linux ~]# cd /usr/local/nginx/conf/vhost/
[root@centos-01linux vhost]# ls
aaa.com.conf test.com.conf
定義test.com.conf日志格式:
[root@centos-01linux vhost]# vim test.com.conf
……
access_log /tmp/test.com.log combined_realip;
#指定日志位置及格式
檢查錯誤:
[root@centos-01linux vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
注: 如果不指定日志格式,系統使用預設日志格式,記錄内容較簡單。
檢測:
[root@centos-01linux vhost]# curl -x127.0.0.1:80 test.com
This is test.com
[root@centos-01linux vhost]# cat /tmp/test.com.log
127.0.0.1 - [30/Mar/2018:09:28:10 +0800] test.com "/" 200 "-" "curl/7.29.0"
12.11 Nginx日志切割
因為Nginx沒有自帶的日志切割工具,是以需要借助系統日志切割指令或使用日志切割腳本。
日志切割腳本
為了友善管理,shell腳本統一儲存位置:/usr/local/sbin/
[root@centos-01linux vhost]# vim /usr/local/sbin/nginx_log_rotate.sh
#! /bin/bash
d=
date -d "-1 day" +%Y%m%d
#定義切割時間(切割一天前的日志)
logdir="/tmp/"
#此處指定要切割的日志路徑(該路徑來自虛拟主機配置檔案)
nginx_pid="/usr/local/nginx/logs/nginx.pid"
#調用pid的目的是執行指令:/bin/kill -HUP
cat $nginx_pid
#該指令等價于指令:nginx -s reload(重新加載檔案),確定與虛拟主機配置檔案變更保持同步
#該位址來自nginx配置檔案
cd $logdir
for log in
ls *.log
do
mv $log $log-$d
done
#此處使用通配進行循環,對所有複合條件的日志檔案進行切割
/bin/kill -HUP
cat $nginx_pid
#執行此指令進行重載生成新的日志檔案來記錄新的日志
執行該腳本:
[root@centos-01linux vhost]# sh -x /usr/local/sbin/nginx_log_rotate.sh
++ date -d '-1 day' +%Y%m%d
- d=20180329
- logdir=/tmp/
- nginx_pid=/usr/local/nginx/logs/nginx.pid
cd /tmp/
++ ls test.com.log
- for log in '
'
ls *.log
mv test.com.log test.com.log-20180329
++ cat /usr/local/nginx/logs/nginx.pid
- /bin/kill -HUP 50929
說明: -x選項的作用是顯示腳本執行過程。
注: 該腳本配合任務計劃cron使用,定期進行切割和清理。
0 0 * /bin/bash /usr/local/sbin/nginx_log_rotate.sh
12.12 靜态檔案不記錄日志&過期時間
核心配置參數:
[root@centos-01linux vhost]# vim test.com.conf
location ~ ..(gif|jpg|jpeg|png|bmp|swf)$
#比對檔案類型
{
expires 7d;
#過期時間為7天
access_log off;
#不記錄該類型檔案的通路日志
}
location ~ ..(js|css)$
expires 12h;
#過期時間為12小時
[root@centos-01linux vhost]# /usr/local/nginx/sbin/nginx -s reload
通路index.html:
[root@centos-01linux vhost]# !curl
curl -x127.0.0.1:80 test.com