nginx自定义错误页需精准配置location=路径、root根目录及intercept开关:error_page仅触发uri请求,必须用location=显式放行该uri,配合root和internal;静态资源需额外location支持;反向代理须启用proxy_intercept_errors。

Linux 下用 Nginx 的 location 配置错误页面,核心不是“路由”而是“精准接管错误响应”,关键在于把错误页文件本身变成一个可被 Nginx 正确服务的资源路径,并确保它不被主规则拦截。
location = /xxx.html 必须单独定义
error_page 指令只是告诉 Nginx “出错时去请求这个 URI”,但这个 URI 本身是否能返回内容,完全取决于有没有对应的 location 块显式放行。漏掉这一步,90% 的自定义页都显示为空白或默认白页。
- 必须用精确匹配:
location = /404.html(等号不能少,否则会误匹配 /404.html?xxx 等非法路径) - 必须指定
root:比如root /usr/share/nginx/html;,Nginx 会自动拼成/usr/share/nginx/html/404.html - 推荐加
internal;:防止用户直接访问/404.html绕过业务逻辑 - 不要用
alias:对=匹配的 location,alias容易路径错位;root更稳
错误页资源要能独立加载
你的 /404.html 里如果引用了 /css/style.css 或 /img/logo.png,这些路径也得有对应 location 支持,否则样式失效、图片 404。
- 最简方案:所有静态资源和错误页放在同一目录,用相对路径引用(如
img/logo.png),并让location = /404.html的root覆盖整个目录 - 若必须用绝对路径(如
/static/css/main.css),就得额外配置:location /static/ { alias /var/www/errors/static/; } - 确保 MIME 类型正确:Nginx 要识别
.html为text/html,检查是否已include mime.types;
区分错误来源,决定要不要开拦截开关
error_page 对静态文件缺失天然生效;但对后端返回的 404/502,Nginx 默认透传,必须手动开启拦截才能触发自定义页。
- 反向代理场景(如 proxy_pass 到 Node.js/Tomcat):在对应
location块里加proxy_intercept_errors on; - FastCGI 场景(如 PHP):在
http或server块加fastcgi_intercept_errors on; - 纯 Nginx 自身错误(如
deny规则触发的 403):不需要拦截开关,但必须保证location = /403.html显式放行且可读
状态码保留与跳转的两种写法
想展示自定义页但保持原始状态码(利于前端识别或 SEO),用标准 error_page;想强制跳转(URL 变、状态码变),要用命名 location 中转。
- 保留 404 状态码并返回页面:
error_page 404 /404.html;(前提是上面三项都满足) - 改成 302 跳首页:
error_page 404 = @tohome;,再配location @tohome { return 302 /; } - 直接跳外部地址:
error_page 404 =302 https://example.com/; - 保留 502 状态码(重要!监控依赖):
error_page 502 =502 /50x.html;











