定位 Nginx 返回 404 Not Found 的问题,通常可以按下面几个步骤系统排查。
先看看响应头:
curl -I http://example.com/test
Server: nginx 且直接 404 → 一般是 Nginx 配置或路径问题最常见原因是 文件路径不对。
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
location /static/ {
alias /data/static/;
}
访问:
/static/a.png
实际路径:
/data/static/a.png
❌ 常见错误:
alias /data/static; # 少了 /
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 想访问哪个文件
Nginx 按 location 优先级匹配:
=^~~ / ~*/示例问题:
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
✅ 检查后端日志或接口是否存在
try_files $uri $uri/ /index.html;
如果少了最后一项,可能直接 404。
有时文件存在,但 Nginx 无权限:
ps aux | grep nginx
确认 worker 用户(如 www-data)
chown -R www-data:www-data /var/www/html
chmod 755 /var/www/html
如果你愿意,可以把:
贴出来,我可以帮你 精准定位是哪一行配置导致 404。