1 访问日志
日志格式
vim /usr/local/nginx/conf/nginx.conf //搜索log_format
其中
这段就是日志格式
除了在主配置文件nginx.conf里定义日志格式外,还需要在虚拟主机配置文件中增加
[root@linux01 ~]# vim /usr/local/nginx/conf/vhost/test.com.conf
access_log /tmp/nginx.log combined_realip;
这里的combined_realip
就是在nginx.conf
中定义的日志格式名字
重新加载配置文件-t
&& -s reload
:
[root@linux01 ~]# /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@linux01 ~]# /usr/local/nginx/sbin/nginx -s reload
curl测试:
[root@linux01 ~]# curl -x127.0.0.1:80 test1.com -I
[root@linux01 ~]# curl -x127.0.0.1:80 test.com -I
[root@linux01 ~]# curl -x127.0.0.1:80 test2.com -I
查看日志:
[root@linux01 ~]# cat /tmp/nginx.log
127.0.0.1 - [19/Nov/2018:09:43:52 +0800] test1.com "/" 301 "-" "curl/7.29.0"
127.0.0.1 - [19/Nov/2018:09:43:55 +0800] test.com "/" 200 "-" "curl/7.29.0"
127.0.0.1 - [19/Nov/2018:09:44:00 +0800] test2.com "/" 301 "-" "curl/7.29.0"
2 nginx访问日志切割
自定义shell 脚本切割文件
[root@linux01 ~]# 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日志记录的路径
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 reload
加到系统任务计划
[root@linux01 ~]# crontab -e
0 0 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh
直接执行测试:
[root@linux01 ~]# /bin/bash /usr/local/sbin/nginx_log_rotate.sh
[root@linux01 ~]# ls /tmp/
mysql.sock nginx.log nginx.log-20181118 pear php-fcgi.sock
间隔一段时间删除日志
[root@linux01 ~]# find /tmp/ -name "*.log-**" -type f -mtime -1 | xargs rm
3 静态文件不记录日志和过期时间
配置如下
[root@linux01 ~]# vim /usr/local/nginx/conf/vhost/test.com.conf
{
listen 80;
server_name test.com test1.com test2.com;
root /data/wwwroot/test.com;
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ //~表示匹配
{
expires 7d;
access_log off; //表示不记录日志
}
location ~ .*\.(js|css)$
{
expires 12h;
access_log off;
}
access_log /tmp/nginx.log combined_realip;
}
重新加载配置文件:
[root@linux01 ~]# /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@linux01 ~]# /usr/local/nginx/sbin/nginx -s reload
创建测试文件:
[root@linux01 ~]# cd /data/wwwroot/test.com/
[root@linux01 test.com]# vim 1.png
[root@linux01 test.com]# vim 2.js
crul测试:
[root@linux01 ~]# curl -x127.0.0.1:80 test.com/1.png
hello
[root@linux01 ~]# curl -x127.0.0.1:80 test.com/2.js
world
[root@linux01 ~]# curl -x127.0.0.1:80 test.com
“test.com”
[root@linux01 ~]# cat /tmp/nginx.log
127.0.0.1 - [19/Nov/2018:10:03:13 +0800] test.com "/" 200 "-" "www.baidu.com"
127.0.0.1 - [19/Nov/2018:10:04:00 +0800] test.com "/" 200 "-" "curl/7.29.0"
过滤了后缀.png
和.js
的访问记录
查看访问文件的过期时间:
[root@linux01 ~]# curl -x127.0.0.1:80 test.com/2.js -I
过期时间:43200秒为12h