温馨提示×

nginx日志为何出现404

小樊
38
2026-09-11 13:21:54
栏目: 编程语言

Nginx 日志中出现 404(Not Found) 通常表示客户端请求的资源在服务器上不存在或不可访问。下面按常见原因分类说明,并给出排查思路。


一、最常见原因

1. 请求的路径确实不存在

  • 访问的 URL 路径写错
  • 文件或目录在服务器上不存在

示例

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

请求:

/images/logo.png

实际文件应为:

/var/www/html/images/logo.png

如果文件不存在 → 404

✅ 排查:

ls -l /var/www/html/images/logo.png

2. root / alias 配置错误(非常常见)

root 示例(容易误解)

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

请求 /static/a.txt
实际找的是:

/data/www/static/a.txt

alias 示例

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

请求 /static/a.txt
实际找的是:

/data/www/a.txt

❌ 常见错误:

  • alias 路径少了 /
  • root 和 alias 混用

3. index 文件缺失

location / {
    root /var/www/html;
    index index.html;
}

如果:

/var/www/html/index.html

不存在 → 404


4. 反向代理返回 404

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

此时 404 可能来自后端服务,不是 Nginx 本身。

✅ 检查:

  • 后端是否启动
  • 后端路由是否存在
  • proxy_pass 是否带 /

5. try_files 配置导致 404

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

如果:

  • 文件不存在
  • 目录不存在
  • 没有 rewrite

→ 直接 404


二、权限问题(隐蔽但常见)

即使文件存在,也可能 404:

  • Nginx 用户无读权限
  • 目录无执行权限(x)

✅ 检查:

ps aux | grep nginx
ls -ld /var/www/html
ls -l /var/www/html/index.html

三、URL 重写 / 路由问题

SPA(Vue / React)

location / {
    try_files $uri /index.html;
}

如果写成:

try_files $uri =404;

→ 前端路由刷新就 404


四、Nginx 配置未生效

  • 修改配置后未 reload
nginx -t
nginx -s reload

五、如何快速定位 404 来源

1. 看 access.log

GET /test.html HTTP/1.1 404

确认请求路径

2. 看 error.log

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

直接告诉你文件不存在


六、一句话总结

Nginx 404 = 请求的资源在指定路径下找不到

排查顺序建议:

  1. 看 error.log 报的路径
  2. 确认文件是否真的存在
  3. 检查 root / alias
  4. 检查权限
  5. 检查是否是后端返回的 404

如果你愿意,可以把 Nginx 配置 + 具体 404 的访问 URL + error.log 片段发出来,我可以帮你精准定位。

0