温馨提示×

如何定位nginx 404错误

小樊
52
2026-10-17 06:44:25
栏目: 编程语言

定位 Nginx 返回 404 Not Found 的问题,通常可以按下面几个步骤系统排查。


一、确认 404 是 Nginx 返回的,还是后端返回的

先看看响应头:

curl -I http://example.com/test
  • Server: nginx 且直接 404 → 一般是 Nginx 配置或路径问题
  • 如果是反向代理(proxy_pass),也可能是 后端应用返回 404

二、检查 Nginx 配置中的 root / alias

最常见原因是 文件路径不对。

1. root 配置

server {
    listen 80;
    server_name example.com;

    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

访问:

/test.html

实际查找:

/var/www/html/test.html

✅ 检查:

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

2. alias 配置(容易出错)

location /static/ {
    alias /data/static/;
}

访问:

/static/a.png

实际路径:

/data/static/a.png

❌ 常见错误:

alias /data/static;  # 少了 /

三、查看 Nginx 错误日志(最关键)

tail -f /var/log/nginx/error.log

典型 404 日志:

2024/01/01 10:00:00 [error] 1234#0: *1 open() "/var/www/html/test.html" failed (2: No such file or directory)

→ 直接告诉你 Nginx 想访问哪个文件


四、检查 location 匹配规则

Nginx 按 location 优先级匹配:

  1. =
  2. ^~
  3. ~ / ~*
  4. /

示例问题:

location /api/ {
    proxy_pass http://backend;
}

location / {
    try_files $uri =404;
}

如果 /api/test 被错误匹配到 location /,就会 404。

✅ 用:

nginx -T

查看 最终生效配置


五、反向代理场景

如果是:

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

访问 /api/user → 后端收到 /user

❌ 如果后端没有 /user,就会 404

✅ 检查后端日志或接口是否存在


六、rewrite / try_files 问题

try_files $uri $uri/ /index.html;

如果少了最后一项,可能直接 404。


七、权限问题(伪装成 404)

有时文件存在,但 Nginx 无权限:

ps aux | grep nginx

确认 worker 用户(如 www-data)

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

八、快速排查清单 ✅

  • [ ] 文件是否真实存在
  • [ ] root / alias 路径是否正确
  • [ ] error.log 报错路径
  • [ ] location 是否匹配预期
  • [ ] 反向代理路径是否一致
  • [ ] 文件权限是否正确

如果你愿意,可以把:

  • Nginx 配置
  • 访问 URL
  • error.log 报错

贴出来,我可以帮你 精准定位是哪一行配置导致 404。

0 踩