You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为所有404请求统一使用自定义错误页面

解决NGINX统一自定义404页面的问题

问题根源

  1. 原配置中,/api/v1/ 路径下的请求被代理到后端服务,但后端返回404时,NGINX默认会直接转发后端的错误响应,不会触发全局的error_page规则,所以显示NGINX默认404页。
  2. 你添加的try_files $uri =404是错误的:它会优先检查本地文件系统是否存在对应资源,而/api/v1/的资源都在后端服务里,本地没有,所以哪怕是有效端点也会直接触发404,返回自定义页面。

正确解决方案

在/api/v1/的location块中添加proxy_intercept_errors on;指令,让NGINX拦截后端返回的错误状态码,从而应用全局的自定义404规则。

修改后的完整配置:

server {
    listen 80;
    listen [::]:80;
    server_name domain.name www.domain.name;

    root /var/www/domain.name/public_html;
    error_page 404 /not_found.html;

    location /api/v1/ {
        proxy_pass http://localhost:8080/;
        proxy_intercept_errors on; # 新增这一行
        limit_except GET HEAD { deny all; }
    }

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

    location = /not_found.html {
        internal;
    }
}

原理说明

  • proxy_intercept_errors on; 会让NGINX捕获后端返回的所有状态码≥300的响应,然后按照server级的error_page配置处理,这样后端返回404时就会跳转到你的自定义页面。
  • 正常的200响应不会被拦截,所以/api/v1/hello这类有效端点依然能正常返回"Hello, World!"。
  • 保留location = /not_found.html的internal属性,确保自定义404页面只能由NGINX内部跳转访问,不能直接通过URL打开。

内容的提问来源于stack exchange,提问作者Saurabh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:20:34