温馨提示×

为何nginx日志出现404错误

小樊
38
2026-09-14 18:01:38
栏目: 编程语言

Nginx 日志中出现 404 Not Found 错误,通常表示客户端请求的资源在服务器上不存在或无法被定位。下面从常见原因到排查思路系统说明。


一、最常见原因

1. 请求路径确实不存在

  • 文件或目录在服务器上不存在
  • URL 拼写错误(大小写敏感,Linux 下尤其重要)

示例:

location /api/ {
    root /data/www;
}

请求 /api/test.html → 实际查找 /data/www/api/test.html


2. root / alias 配置错误(高频)

❌ root 用错

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

请求 /static/a.png → /data/static/static/a.png(多一层)

✅ 正确:

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

3. index 文件未配置

未设置默认首页:

location / {
    # 没有 index index.html;
}

访问 / 可能 404

✅ 修复:

index index.html index.php;

4. try_files 配置不当

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

若文件不存在直接返回 404

前端 SPA(Vue/React)应:

try_files $uri /index.html;

5. 反向代理返回 404

后端服务返回 404,Nginx 只是“转发者”

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

→ 检查后端日志


6. 权限问题(少见但隐蔽)

  • 文件存在但 Nginx 无读取权限
  • 通常表现为 403,但某些情况会 404

检查:

ls -l /path/to/file
ps aux | grep nginx

二、快速排查步骤

1️⃣ 看 Nginx 错误日志

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

通常会显示:

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

2️⃣ 确认请求 URL

curl -I http://域名/path

3️⃣ 检查对应 location

location /xxx/ {
    ...
}

4️⃣ 确认文件真实路径

realpath /path

三、典型场景速查表

场景 原因
网站首页 404 未配置 index
静态资源 404 root/alias 用错
API 404 后端返回或路径不匹配
SPA 刷新 404 未 try_files 到 index.html
偶发 404 负载均衡到不同节点

四、如果你愿意

你可以贴出:

  • Nginx 配置片段
  • 访问的 URL
  • error.log 相关日志

我可以帮你精确判断是哪一类 404。

0 踩