温馨提示×

为什么nginx日志出现404

小樊
44
2026-10-14 10:47:08
栏目: 编程语言

Nginx 日志里出现 404(Not Found),通常表示:客户端请求的资源在服务器上找不到。原因可以从「请求本身」和「Nginx 配置」两方面来看。


一、最常见原因

1. 请求路径确实不存在

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

示例:

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

请求 /static/a.png
→ 实际找的是 /var/www/html/static/a.png

如果文件在 /var/www/html/a.png,就会 404。


2. root 和 alias 用错(非常常见)

❌ root 误用

location /img/ {
    root /var/www/img;
}

请求 /img/1.jpg
→ /var/www/img/img/1.jpg(多了一层)

✅ 应该用 alias

location /img/ {
    alias /var/www/img/;
}

3. index 文件未配置

访问目录但没指定文件:

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

如果目录里没有 index.html,会 404(或 403,取决于配置)

解决:

index index.html index.php;

4. 前端路由(SPA)未 fallback

Vue / React 路由刷新 404:

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

5. PHP / 后端接口 404

  • fastcgi_pass 配置错误
  • SCRIPT_FILENAME 指向错误
  • 路由未匹配

示例(PHP):

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

6. 反向代理返回 404

后端服务本身返回 404,Nginx 只是“转发”:

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

要看 后端日志,不是 Nginx 的问题。


7. 域名 / server_name 不匹配

请求没命中正确的 server 块,走了默认配置。


二、如何快速排查

1. 看日志

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

关注:

  • 请求的 URL
  • $request_filename(实际文件路径)

2. 打开 debug(临时)

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

3. 测试配置

nginx -t

三、一句话总结

Nginx 404 = 请求的资源在「当前配置指向的位置」不存在

如果你愿意,可以把:

  • 404 的 URL
  • 对应 location 配置
  • 文件实际路径

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

0 踩