如何禁用Nginx在access.log中记录404请求日志?
禁用Nginx access.log中的404请求日志
我最近在Nginx配置里添加了log_not_found指令,它能有效阻止error.log记录404日志,但access.log里还是会生成404请求日志,请问如何禁用access.log中的404日志?
示例日志
172.18.xx.xx - - [02/Sep/2024:11:38:00 +0000] "GET /test HTTP/2.0" 404 131 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36" "219.100.xx.xx"
当前Nginx配置
http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; server { listen 443 ssl; root /example/path/html; log_not_found off; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log warn; location / { add_header "Access-Control-Allow-Origin" "*" always; try_files $uri =404; } } }
解决方案
要过滤access.log中的404日志,推荐用map指令定义条件变量(性能更优),具体操作如下:
- 在
http块中添加map配置,根据响应状态码生成过滤变量:
map $status $not_404 { ~^404 0; # 状态码为404时,变量值设为0 default 1; # 其他状态码设为1 }
- 修改
server块中的access_log指令,加入if=$not_404条件——只有当变量值为1时才记录日志:
access_log /var/log/nginx/access.log main if=$not_404;
修改后的完整配置
http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; map $status $not_404 { ~^404 0; default 1; } server { listen 443 ssl; root /example/path/html; log_not_found off; access_log /var/log/nginx/access.log main if=$not_404; error_log /var/log/nginx/error.log warn; location / { add_header "Access-Control-Allow-Origin" "*" always; try_files $uri =404; } } }
生效方式
修改完成后,重载Nginx配置即可生效:
nginx -s reload
内容的提问来源于stack exchange,提问作者x90nik
相关产品推荐
相关产品推荐

