log_not_found用于控制error_log中“文件未找到”warn日志是否记录,默认on;设为off可避免SPA等场景下因静态资源缺失导致的日志刷屏,但不影响404响应及access_log记录。

log_not_found 是 Nginx 控制“文件未找到”类 warn 日志是否写入 error_log 的关键指令,它不干预 404 响应本身,也不影响 access_log 中的状态码记录,专用于缓解因静态资源缺失导致的 error_log 刷屏问题。
log_not_found 的作用对象很明确
它只屏蔽由文件系统访问失败触发的 error_log 条目,典型如:
- open() "/var/www/html/js/app.abc.js" failed (2: No such file or directory)
- stat() "/var/www/html/images/logo.png" failed (2: No such file or directory)
这类日志通常出现在 try_files、alias、root 查找静态资源失败时。只要请求最终返回了 404(或被回退到 index.html),且错误根源是路径下无对应文件,log_not_found 就能管住它。
为什么 SPA 场景下特别需要关掉它
Vue/React 使用 history 模式后,前端路由会生成大量类似 /user/profile、/dashboard/stats 的路径。Nginx 默认按真实文件查找,找不到就记一条 warn 日志——哪怕最终通过 try_files $uri $uri/ /index.html 正常返回了 200,中间的“查不到”过程仍会刷屏 error_log。
只需在对应 location 中加一句:
location / {
log_not_found off;
try_files $uri $uri/ /index.html;
}
这样既保留完整路由能力,又让 error_log 干净可读。注意:该指令支持 http/server/location 多级配置,优先级从高到低为 location → server → http。
别和 access_log 的 404 记录搞混
log_not_found off 后,error_log 不再输出“No such file”,但 access_log 里依然会如实记录 404 状态码,例如:
192.168.1.100 - - [08/May/2026:03:15:22 +0000] "GET /assets/missing.css HTTP/1.1" 404 153 "-" "Mozilla/5.0..."
如果你也想过滤掉某些特定 404(比如健康检查 /healthz 或爬虫 /robots.txt),得用 map 配合 access_log 条件记录,例如:
map $request_uri $loggable {
~^/(healthz|robots\.txt)$ 0;
default 1;
}
access_log /var/log/nginx/access.log main if=$loggable;
几个实用配置建议
- 对纯静态资源 location(如
location ~* \.(js|css|png|gif)$),建议显式配log_not_found off,避免因构建哈希名变更、清理旧资源等引发日志风暴 - 若某 location 下所有 404 都属预期行为(如 fallback 到 CDN 或统一错误页),可直接关闭,无需逐条判断
- 关闭前确认该 location 确实不依赖 error_log 排查真实部署缺失问题;生产环境建议保留根 location 的 log_not_found on,仅在子路径中精细化关闭
- 搭配
error_page 404 /404.html和location = /404.html内部处理,可进一步统一响应体验,且不影响日志策略










