温馨提示×

为什么linux nginx报404

小樊
47
2026-10-19 14:20:43
栏目: 智能运维

Linux 下 Nginx 报 404 Not Found 是非常常见的问题,原因通常集中在路径、配置、权限、rewrite 这几类。下面按「最常见 → 较少见」帮你系统梳理。


一、最常见原因(90% 的情况)

1️⃣ root / alias 路径写错

这是 最常见的 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

确认路径是否一致。


2️⃣ 文件真的不存在

Nginx 不会帮你“猜测”文件。

检查:

ls /var/www/html

如果没 index.html:

touch /var/www/html/index.html

3️⃣ index 指令没配置或写错

location / {
    root /var/www/html;
    # 缺少 index
}

✅ 正确:

index index.html index.htm;

4️⃣ 权限问题(非常容易被忽略)

Nginx 一般以 www-data 或 nginx 用户运行。

检查:

ps aux | grep nginx

修复权限:

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

二、location 配置导致 404

5️⃣ location 匹配错误

例如:

location /api {
    root /var/www/html;
}

访问:

/abc → 404

原因:location /api 只匹配 /api 开头的路径。


6️⃣ alias 使用错误(高频坑)

❌ 错误:

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

访问 /static/file.png → 实际找 /data/static//file.png

✅ 正确:

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

或:

location /static {
    alias /data/static;
}

三、Rewrite / 反向代理问题

7️⃣ try_files 配置不当

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

如果:

  • 没有 index.html
  • 没有后端服务

→ 必然 404


8️⃣ 反向代理后端挂了

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

后端没启动:

curl http://127.0.0.1:8080

四、如何快速定位(强烈推荐)

看 Nginx 错误日志(最重要)

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

你会看到类似:

open() "/var/www/html/index.html" failed (2: No such file or directory)

打开 debug 日志(可选)

error_log /var/log/nginx/error.log debug;

五、快速自查清单 ✅

  • [ ] 文件是否存在
  • [ ] root / alias 路径是否一致
  • [ ] index 是否配置
  • [ ] 文件权限是否正确
  • [ ] error.log 报错信息
  • [ ] location 是否匹配请求路径

如果你愿意,可以把:

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

发出来,我可以直接帮你精准定位是哪一条原因。

0 踩