Linux 下 Nginx 报 404 Not Found 是非常常见的问题,原因通常集中在路径、配置、权限、rewrite 这几类。下面按「最常见 → 较少见」帮你系统梳理。
这是 最常见的 404 原因。
示例错误:
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
}
但你的文件其实在:
/var/www/html/index.html ❌ 不存在
实际是:
/srv/www/index.html
✅ 解决:
ls -l /var/www/html
确认路径是否一致。
Nginx 不会帮你“猜测”文件。
检查:
ls /var/www/html
如果没 index.html:
touch /var/www/html/index.html
location / {
root /var/www/html;
# 缺少 index
}
✅ 正确:
index index.html index.htm;
Nginx 一般以 www-data 或 nginx 用户运行。
检查:
ps aux | grep nginx
修复权限:
chown -R www-data:www-data /var/www/html
chmod -R 755 /var/www/html
例如:
location /api {
root /var/www/html;
}
访问:
/abc → 404
原因:location /api 只匹配 /api 开头的路径。
❌ 错误:
location /static/ {
alias /data/static/;
}
访问 /static/file.png → 实际找 /data/static//file.png
✅ 正确:
location /static/ {
alias /data/static/;
}
或:
location /static {
alias /data/static;
}
location / {
try_files $uri $uri/ =404;
}
如果:
index.html→ 必然 404
location /api/ {
proxy_pass http://127.0.0.1:8080;
}
后端没启动:
curl http://127.0.0.1:8080
tail -f /var/log/nginx/error.log
你会看到类似:
open() "/var/www/html/index.html" failed (2: No such file or directory)
error_log /var/log/nginx/error.log debug;
如果你愿意,可以把:
发出来,我可以直接帮你精准定位是哪一条原因。