Nginx 日志里出现 404 错误,通常意味着 请求的资源在服务器上未找到。但“404”只是一个结果,原因可能有很多种。下面按最常见 → 较少见的顺序帮你系统排查。
现象
GET /test.html HTTP/1.1 404
原因
/test.html 根本不存在排查
ls -l /var/www/html/test.html
✅ Linux 路径 区分大小写
server {
root /var/www/html;
location /static/ {
# 实际访问的是 /var/www/html/static/xxx
}
}
如果你实际文件在:
/var/www/static/xxx
那就永远 404。
✅ 检查:
root /var/www;
或:
location /static/ {
alias /var/www/static/;
}
⚠️ alias 结尾一定要有 /
location /api/ {
proxy_pass http://127.0.0.1:8080;
}
如果后端服务没启动或路径不对,也可能返回 404。
✅ 测试后端是否可用:
curl http://127.0.0.1:8080/xxx
index index.html index.php;
如果目录存在,但:
/var/www/html/index.html ❌
访问 / 就会 404。
✅ 检查:
ls /var/www/html/index.*
location / {
try_files $uri $uri/ =404;
}
如果:
$uri 不存在$uri/ 也不存在就会直接 404。
✅ 单页应用(SPA)常见正确写法:
try_files $uri /index.html;
例如 PHP:
location ~ \.php$ {
fastcgi_pass unix:/run/php/php-fpm.sock;
}
但:
.php 文件不存在也会 404。
✅ 检查:
systemctl status php-fpm
403 或 404(取决于配置)
✅ 检查:
namei -l /var/www/html/test.html
✅ Nginx 运行用户:
ps aux | grep nginx
通常是:
www-data 或 nginx
✅ 修复权限:
chown -R www-data:www-data /var/www/html
chmod -R 755 /var/www/html
rewrite ^/old/(.*)$ /new/$1 last;
如果 /new/xxx 不存在,也会 404。
✅ 用:
nginx -T | grep rewrite
排查规则。
Nginx 只是“转发者”。
✅ 查看 upstream 返回内容:
proxy_intercept_errors on;
或抓包 / 看应用日志。
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
确认:
nginx -T | grep root
nginx -T | grep alias
curl -v http://localhost/xxx
| 现象 | 原因 |
|---|---|
| 静态文件 404 | root / alias 错 |
/ 访问 404 |
index 文件不存在 |
| SPA 刷新 404 | try_files 配置错 |
| API 404 | 代理后端问题 |
| 偶发 404 | rewrite / 权限 |
如果你愿意,可以直接贴出:
我可以帮你 精确定位是哪一行配置导致的 404 ✅