温馨提示×

nginx日志如何排查404

小樊
45
2026-10-02 16:29:03
栏目: 编程语言

排查 Nginx 返回的 404 Not Found,可以按下面系统化的思路来分析和定位问题。


一、先确认 404 是从哪里来的

1. 查看 Nginx 访问日志(access log)

通常位置:

/var/log/nginx/access.log

或

/var/log/nginx/<站点>/access.log

示例:

127.0.0.1 - - [10/Oct/2024:12:00:00 +0800] "GET /api/test HTTP/1.1" 404 153

重点关注:

  • 请求路径:/api/test
  • 状态码:404
  • 请求方法:GET / POST
  • 客户端 IP

2. 判断是 Nginx 返回的,还是后端返回的

  • Nginx 直接返回 404
    • 静态文件不存在
    • location 匹配错误
  • 后端服务返回 404
    • 反向代理配置正确,但后端应用报错

可以在 error log 中确认:

/var/log/nginx/error.log

二、常见 404 原因及排查方法

✅ 1. 静态文件不存在(最常见)

location / {
    root /var/www/html;
}

排查:

ls -l /var/www/html/xxx.html

注意:

  • root 是目录
  • index 是否配置
index index.html index.php;

✅ 2. location 匹配错误

例如:

location /api {
    proxy_pass http://127.0.0.1:8080;
}

请求 /api/user
实际转发到:http://127.0.0.1:8080/api/user

如果你的后端只接受 /user:

location /api/ {
    proxy_pass http://127.0.0.1:8080/;
}

⚠️ proxy_pass 末尾的 / 非常关键


✅ 3. try_files 导致 404

location / {
    try_files $uri $uri/ /index.php?$args;
}

如果:

  • 文件不存在
  • 后端路由也没命中 就会 404

排查:

  • 临时注释 try_files
  • 或加 debug 日志

✅ 4. 反向代理到后端 404

确认:

curl http://127.0.0.1:8080/xxx

如果后端本身就 404:

  • 问题不在 Nginx
  • 检查后端路由、接口路径

✅ 5. 权限问题(伪装成 404)

Nginx 无权访问文件:

open() "/var/www/html/test.html" failed (13: Permission denied)

解决:

chown -R nginx:nginx /var/www/html
chmod 755 /var/www/html

✅ 6. 重写规则问题

rewrite ^/old/(.*)$ /new/$1 last;

如果目标不存在,也会 404

可用:

rewrite_log on;
error_log /var/log/nginx/rewrite.log notice;

三、开启 Nginx Debug 日志(强烈推荐)

error_log /var/log/nginx/error.log debug;

然后:

nginx -t
nginx -s reload

可以看到:

  • location 匹配过程
  • 文件查找路径
  • 代理转发地址

四、快速排查清单 ✅

  • [ ] 请求 URL 是否正确
  • [ ] 文件/目录是否存在
  • [ ] root / alias 是否配错
  • [ ] location 是否匹配
  • [ ] proxy_pass 是否带 /
  • [ ] 后端服务是否正常
  • [ ] 权限是否正确
  • [ ] 是否 try_files / rewrite 导致

五、如果你愿意,我可以直接帮你分析

你可以贴出:

  1. nginx 配置(相关 server / location)
  2. 访问日志中的 404 请求
  3. 你期望访问的 URL 和实际文件/接口

我可以帮你精准定位 ✅

0 踩