温馨提示×

linux nginx为何报404错误

小樊
55
2026-10-29 06:58:27
栏目: 智能运维

在 Linux 上用 Nginx 出现 404 Not Found,通常不是 Nginx 本身坏了,而是请求的资源没匹配到。下面按最常见原因 → 排查方法给你梳理。


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

1️⃣ 网站根目录没有该文件

例如访问:

http://域名/index.html

但 Nginx 配置中:

root /var/www/html;

而 /var/www/html/index.html 不存在

✅ 检查:

ls -l /var/www/html

2️⃣ root / alias 配置错误

❌ 错误示例

location /static/ {
    root /data/static/;
}

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

✅ 正确(用 alias):

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

3️⃣ location 没匹配到

例如:

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

但访问的是:

/api
(少了结尾斜杠)

✅ 建议:

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

4️⃣ index 文件没设置

server {
    root /var/www/html;
    # 没写 index
}

✅ 应该:

index index.html index.php;

二、反向代理 / 接口 404

5️⃣ 后端服务没启动或端口错

proxy_pass http://127.0.0.1:9000;

检查:

curl http://127.0.0.1:9000

6️⃣ 后端返回 404(不是 Nginx 的)

看错误页来源:

curl -I http://域名/xxx

如果是:

Server: nginx

✅ Nginx 的问题
如果是:

Server: Apache / gunicorn / tomcat

✅ 后端的问题


三、权限问题(常被忽略)

7️⃣ Nginx 没权限读文件

ps aux | grep nginx

通常是 www-data 或 nginx

修复:

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

四、配置没生效

8️⃣ 改了配置没重载

nginx -t
systemctl reload nginx

五、快速排查清单 ✅

# 1. 测试配置
nginx -t

# 2. 查看错误日志
tail -f /var/log/nginx/error.log

# 3. 查看访问日志
tail -f /var/log/nginx/access.log

# 4. 本地测试
curl http://127.0.0.1

六、如果你愿意,我可以直接帮你定位

你可以贴出:

  • Nginx 配置(server / location 段)
  • 访问的 URL
  • error.log 相关报错

我可以直接告诉你哪一行配置导致 404。

0 踩