log_not_found 是真实指令,Log-Not-Found(带连字符、首字母大写)不是 Nginx 配置项,会被静默忽略;它控制 notice 及以下级别 error_log 中“file not found”提示的记录,作用域为 http/server/location,需配合 error_log 级别 ≤ notice 才生效。

Log-Not-Found 指令根本不存在于 Nginx
直接说结论:log_not_found 是真实指令,但 Log-Not-Found(带连字符、首字母大写)不是 Nginx 的任何配置项——它既不会生效,也不会报错,只会被 Nginx 静默忽略。你查不到文档、配了也没用,这是最常踩的命名陷阱。
如何真正关闭 404 静态资源的日志记录
log_not_found 是控制是否将 404 Not Found(主要是静态文件缺失)写入 error_log 的开关,但它只影响 error_log 级别为 notice 或更低时的“file not found”提示行,不影响 access_log。
- 默认值是
on,即所有找不到的.js、.png、.ico都会在error_log中记一条open() "/path/to/xxx" failed (2: No such file or directory) - 设为
off后,这类提示不再出现,但其他错误(如权限拒绝、磁盘满)仍照常记录 - 该指令作用域是
http、server、location,推荐在具体location块里关,避免全局掩盖问题
例如,屏蔽 favicon.ico 缺失日志:
location = /favicon.ico {
log_not_found off;
return 204;
}为什么 location 匹配顺序和范围很重要
log_not_found 只对当前作用域内触发的“文件未找到”生效。如果请求没进到你设了 off 的 location,它就不起作用。
- 匹配必须精确或足够前置:用
location = /xxx或location ^~ /static/,避免被更宽泛的location /先捕获 - 注意 alias 和 root 的路径解析差异:如果
alias /data/下没有对应文件,Nginx 仍会报file not found,此时log_not_found off才管用;而root拼接后路径不存在,同样适用 - 不要在
try_files后还指望它:如果try_files $uri @fallback走到了@fallback,那缺失判定发生在try_files阶段,log_not_found对@fallback内部不生效
替代方案:用 map + error_page 更精细地过滤
当你要按文件类型(比如只关 .webp 缺失日志,保留 .js)或按 User-Agent 过滤时,log_not_found 就不够用了。这时得靠 map 配合 error_page 把特定 404 “消化”掉:
map $sent_http_content_type $log_404 {
"~*image/webp" 0;
default 1;
}
server {
error_page 404 = @silent_404;
location @silent_404 {
internal;
log_not_found off;
return 404;
}
# 同时在 http 或 server 级设置:
# error_log /var/log/nginx/error.log notice;
# 因为 log_not_found 只在 notice 及以下级别起效
}这个方案本质是把 404 主动转成内部跳转,再关日志——但要注意:log_not_found 在 @named_location 里依然有效,且必须配合 internal,否则可能引发循环。
真正容易被忽略的是:Nginx 的 error_log 默认级别是 error,而 log_not_found 只影响 notice 级别的“file not found”消息。如果你的 error_log 级别设成了 info 或 debug,那关了也没用——得先确认日志级别。


















