Nginx 1.14.1中error_page配置404无效,如何设置自定义响应?
Nginx 404自定义返回内容解决方案
问题根源
你的配置中所有请求通过proxy_pass转发到上游服务localhost:8080,默认情况下Nginx会直接透传上游返回的404响应,不会触发自身的error_page规则;另外,原error_page指定的绝对路径如果文件不存在或权限不足,也会导致规则失效。
替代解决方案
方案1:直接返回指定字符串(最贴合需求)
通过定义内部跳转location,直接返回"IT WORKS"文本,同时开启拦截上游错误响应:
修改你的server配置块,添加以下内容:
server { # 保留原有其他配置... # 开启拦截上游返回的错误状态码,确保Nginx处理404 proxy_intercept_errors on; # 将404错误指向自定义内部location error_page 404 @custom404; # 定义自定义404响应 location @custom404 { return 404 "IT WORKS"; # 指定响应内容类型为纯文本 add_header Content-Type text/plain; } location / { # 保留原有proxy相关配置... } }
方案2:修复原静态页面路径问题(如果仍想用静态文件)
若要继续使用静态页面,确保文件路径正确并限制外部直接访问:
server { # 保留原有其他配置... proxy_intercept_errors on; error_page 404 /404.html; # 配置404.html的访问路径,设置为内部仅允许Nginx调用 location = /404.html { root /usr/share/nginx/html; internal; } }
注意:需确保
/usr/share/nginx/html/404.html文件存在,且Nginx进程对其有读取权限,可执行ls -l /usr/share/nginx/html/404.html验证。
方案3:针对特定路径单独处理404
如果仅需对部分路径返回自定义404,可在对应location内配置:
location /some-path/ { proxy_pass http://app; proxy_intercept_errors on; error_page 404 @custom404; } location @custom404 { return 404 "IT WORKS"; add_header Content-Type text/plain; }
验证配置
修改完成后,执行以下命令检查配置语法并重启Nginx:
nginx -t systemctl restart nginx
内容的提问来源于stack exchange,提问作者Emrahall
相关产品推荐
相关产品推荐

