温馨提示×

nginx日志为何显示404

小樊
37
2026-09-29 19:17:58
栏目: 编程语言

Nginx 日志中出现 404(Not Found) 通常意味着:客户端请求的资源在服务器上不存在,或 Nginx 没有正确匹配到该资源。下面按常见原因逐个说明,并给出排查方法。


一、最常见原因

1️⃣ 请求的路径在服务器上不存在

例如:

GET /images/logo.png HTTP/1.1 404

但服务器上:

/var/www/html/images/logo.png 不存在

✅ 排查:

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

或修改 nginx 配置后确认 root 路径是否正确。


2️⃣ Nginx root 或 alias 配置错误

错误示例:

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

实际访问:

/static/a.png → /var/www/html/static/static/a.png

✅ 正确写法:

location /static/ {
    alias /var/www/html/static/;
}

或:

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

3️⃣ location 匹配不到请求

例如:

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

但请求的是:

/api/user/

而未加 /

✅ 建议:

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

4️⃣ 反向代理后端返回 404

Nginx 本身没问题,是后端应用返回 404。

日志示例:

GET /api/user HTTP/1.1 404

但 Nginx 配置正常。

✅ 排查:

curl http://127.0.0.1:8080/api/user

5️⃣ index 文件缺失

访问目录但无 index 文件:

GET / HTTP/1.1 404

✅ 检查:

index index.html index.php;
ls /var/www/html/index.html

6️⃣ 静态资源被 try_files 拦截

常见配置:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

如果:

  • index.php 不存在
  • PHP 未运行

就会 404。


二、如何快速定位问题

✅ 查看 access 日志

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

看:

  • 请求路径
  • 状态码
  • user-agent

✅ 查看 error 日志

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

常见提示:

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

三、典型 404 场景速查表

场景 原因
首页 404 index 文件缺失
图片 404 root/alias 错
API 404 后端未启动 / 路由错误
偶发 404 try_files 配置问题
带后缀 404 location 正则不匹配

四、如果你愿意,我可以直接帮你分析

你可以贴出:

  1. nginx 配置(server / location)
  2. 访问的 URL
  3. access / error 日志片段

我可以直接告诉你 为什么会 404 以及如何改。

0 踩