nginx 自定义 404 页面需三步:开启错误拦截(proxy_intercept_errors 或 fastcgi_intercept_errors)、正确配置 error_page 与 location(推荐 alias + internal)、确保文件存在且权限正确;spa 场景需按扩展名分流,避免覆盖前端路由。

静态资源服务配置自定义 404 页面,核心是让 Nginx 在真正找不到文件时,不返回默认错误页,而是返回你准备好的 HTML 文件,同时保持 404 状态码。它不依赖后端,纯网关层处理,关键在三件事:拦截开关、路径定位、页面可访问。
必须开启拦截开关
仅写 error_page 404 /404.html 不生效——Nginx 默认会把上游(比如 try_files 未命中)产生的 404 直接透传出去。你需要告诉它:“我来接管”。
- 如果是纯静态服务(无 proxy_pass、无 fastcgi_pass),一般不需要额外开关,但要确认没被
try_files覆盖逻辑 - 如果用了
try_files(常见于 Vue/React 部署),确保它只 fallback 到index.html,而真实缺失的图片、CSS、JS 才触发 404:try_files $uri $uri/ /index.html;→ 这行会让所有路径都落到 index.html,掩盖真实 404;应改为try_files $uri $uri/ =404;或更稳妥地按扩展名分流 - 若反向代理后端(如 Node/Java),需在对应
location块中加:proxy_intercept_errors on; - 若对接 PHP-FPM,需在
http或server块中加:fastcgi_intercept_errors on;
正确设置 error_page 和 location
error_page 后面的路径是 URI 路径,不是磁盘路径。它最终指向哪个文件,取决于所在作用域里的 root 或 alias。
- 推荐统一用
alias指向专用错误页目录,避免和主站 root 冲突:location = /404.html { alias /var/www/errors/404.html; } - 如果用
root,注意拼接规则:root /var/www/html;+error_page 404 /404.html;→ 实际读取/var/www/html/404.html -
location = /404.html必须显式声明,并加上internal;,防止用户直接访问该路径 - 确保该 location 中 MIME 类型正确,可加:
types { text/html html; }或确认已include mime.types;
确保文件存在且权限正确
错误页本身是静态文件,但 Nginx 必须能读到它,否则会二次报错或返回空白。
- 把
404.html放在你指定的路径下(如/var/www/errors/404.html) - 检查文件权限:Nginx 工作进程(通常是
www-data或nginx用户)要有读取权限
(例如:chmod 644 /var/www/errors/404.html,chown www-data:www-data /var/www/errors/404.html) - 不要用绝对路径写在
error_page指令里,比如error_page 404 /usr/share/nginx/html/404.html;—— 这会被当作 URI 处理,导致 404 嵌套 - 配置改完后,务必运行
nginx -t测试语法,再nginx -s reload生效
区分真实 404 和前端路由 fallback
在 SPA(如 Vue Router history 模式)场景下,不能让所有未命中都进 404,否则合法子路径(如 /user/profile)也会被拦截。
- 先匹配静态资源:对带常见后缀(.js、.css、.png、.woff2 等)的请求,直接
try_files $uri =404; - 再处理无后缀路径:用命名 location fallback 到
index.html,仅当该文件存在才返回location / { try_files $uri $uri/ @router; }<br>location @router { rewrite ^(.*)$ /index.html last; } - 这样,只有真实缺失的静态资源(如
/img/logo.xxx)才会走到 Nginx 默认 404,进而触发你的error_page











