vim /usr/local/nginx/conf/nginx.conf //搜索log_format
$remote_addrphp |
客戶端IP(公網IP)css |
$http_x_forwarded_forhtml |
代理服務器的IPlinux |
$time_localnginx |
服務器本地時間shell |
$hostvim |
訪問主機名(域名)bash |
$request_uri服務器 |
訪問的url地址curl |
$status |
狀態碼 |
$http_referer |
訪問前的源地址 |
$http_user_agent |
用戶代理 |
除了在主配置文件nginx.conf裏定義日誌格式外,還須要在虛擬主機配置文件中進行修改
server { listen 80; server_name test.com test1.com test2.com; index index.html index.htm index.php; root /data/wwwroot/test.com; if ($host != 'test.com' ) { rewrite ^/(.*)$ http://test.com/$1 permanent; } access_log /tmp/1.log lemlog; //這裏的lemlog就是在nginx.conf中定義的日誌格式名字 }
-t -s reload
[root@linux-10 ~]# curl -x 127.0.0.1:80 test.com -I HTTP/1.1 200 OK Server: nginx/1.14.0 Date: Sat, 09 Jun 2018 02:47:16 GMT Content-Type: text/html Content-Length: 27 Last-Modified: Fri, 08 Jun 2018 04:35:18 GMT Connection: keep-alive ETag: "5b1a0786-1b" Accept-Ranges: bytes [root@linux-10 ~]# cat /tmp/1.log 127.0.0.1 - [09/Jun/2018:10:47:16 +0800] test.com "/" 200 "-" "curl/7.29.0"
Nginx日誌切割可經過編寫shell腳本的方式實現
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" //獲取Nginx的pid,爲了讓腳本實現Nginx從新加載 cd $logdir for log in `ls *.log` do mv $log $log-$d done /bin/kill -HUP `cat $nginx_pid` //Nginx從新加載,生成新的配置文件
編寫任務計劃,規定日誌切割的時間(shell腳本的執行時間)
0 0 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ //匹配相關文件 { expires 7d; //配置過時時間 access_log off; //不記錄日誌 } location ~ .*\.(js|css)$ { expires 12h; access_log off; }
建立測試文件並測試效果
[root@linux-10 ~]# curl -x 127.0.0.1:80 test.com/123.png afdsfsfsdfsdfsddfs [root@linux-10 ~]# curl -x 127.0.0.1:80 test.com 「This is a test site.」 [root@linux-10 ~]# cat /tmp/1.log 127.0.0.1 - [09/Jun/2018:10:47:16 +0800] test.com "/" 200 "-" "curl/7.29.0"
日誌只記錄了訪問主頁的行爲。