Nginx 日志中出现 404 Not Found 错误,通常表示客户端请求的资源在服务器上不存在或无法被定位。下面从常见原因到排查思路系统说明。
示例:
location /api/ {
root /data/www;
}
请求 /api/test.html → 实际查找 /data/www/api/test.html
location /static/ {
root /data/static;
}
请求 /static/a.png → /data/static/static/a.png(多一层)
✅ 正确:
location /static/ {
alias /data/static/;
}
未设置默认首页:
location / {
# 没有 index index.html;
}
访问 / 可能 404
✅ 修复:
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
若文件不存在直接返回 404
前端 SPA(Vue/React)应:
try_files $uri /index.html;
后端服务返回 404,Nginx 只是“转发者”
location /api/ {
proxy_pass http://127.0.0.1:8080;
}
→ 检查后端日志
检查:
ls -l /path/to/file
ps aux | grep nginx
tail -f /var/log/nginx/error.log
通常会显示:
open() "/data/www/test.html" failed (2: No such file or directory)
curl -I http://域名/path
location /xxx/ {
...
}
realpath /path
| 场景 | 原因 |
|---|---|
| 网站首页 404 | 未配置 index |
| 静态资源 404 | root/alias 用错 |
| API 404 | 后端返回或路径不匹配 |
| SPA 刷新 404 | 未 try_files 到 index.html |
| 偶发 404 | 负载均衡到不同节点 |
你可以贴出:
我可以帮你精确判断是哪一类 404。