nginx访问日志过滤
1).nginx访问日志的过滤-不记录不重要的日志:
一个网站,会包含很多元素,尤其是有大量的图片、js、css等静态元素。这样的请求其实可以不用记录日志,也没啥用。如果记录,日志可能会很大,而且没用。
配置示例:下面3种,效果一样:
location ~* '(gif|jpg|png|css|js|rar|mp4|bmp)$'
{
access_log off;
}
或:
location ~* ^.+\.(gif|jpg|png|css|js|rar|mp4|bmp)$
{
access_log off;
}
或:
location ~* ^.+\.(gif|jpg|png|css|js|rar|mp4|bmp)$
{
access_log /dev/null;
}
2).nginx访问日志过滤示例详解:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
http {
...
log_format main '$http_x_forwarded_for|$http_x_real_ip|$remote_addr $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer"'
'"$http_user_agent"';
access_log logs/access.log main;
include vhost/*.conf;
...
}
[root@localhost ~]# cat /usr/local/nginx/conf/vhost/www.1.conf
server{
listen 80;
server_name www.1.com;
root /data/wwwroot/www.1.com;
index index.html;
location ~* '(gif|jpg|png|css|js|rar|mp4|bmp)$'
{
access_log off;
}
}
[root@localhost ~]# /usr/local/nginx/sbin/nginx -s reload
[root@localhost ~]# > /usr/local/nginx/logs/access.log
客户端访问:
[root@localhost ~]# cat /etc/hosts
192.168.171.132 www.1.com
[root@localhost ~]# curl www.1.com/xxx.css1 #不匹配,会记录
<html>
<head><title>404 Not Found</title></head>
服务器查看访问日志:
[root@localhost ~]# cat /usr/local/nginx/logs/access.log
-|-|192.168.171.131 - [27/Dec/2020:10:02:28 +0800] "GET /xxx.css1 HTTP/1.1" 404 153 "-""curl/7.29.0"
[root@localhost ~]# > /usr/local/nginx/logs/access.log
客户端访问:
[root@localhost ~]# cat /etc/hosts
192.168.171.132 www.1.com
[root@localhost ~]# curl www.1.com/xxx.css #匹配,不会记录
<html>
<head><title>404 Not Found</title></head>
服务器查看访问日志:
[root@localhost ~]# cat /usr/local/nginx/logs/access.log
空
nginx访问日志过滤参考链接: https://github.com/aminglinux/nginx/blob/master/log/filter.md