为什么nginx error_page遇到后端错误时不跳转?

 nginx不得不说的参数之 proxy_intercept_errors与fastcgi_intercept_errors

     为什么我的error_page 配置没有生效,没有正常跳转?我也遇到过这个问题,所以这才促使我对proxy_intercept_errors与fastcgi_intercept_errors这两个参数做了详细的了解。

  由于我们商户和点评信息相关web应用是给用户做消费决策的商户和相关点评等信息,浏览功能一般比互动功能要重要一些,但是由于一些内部出错可能会导致整个应用出现异常,导致用户无法浏览到商户的相关信息。

 为了提升商户页面的可用性,我们通过静态抓取现有页面保存在静态文件服务器上,在应用服务器nginx上配置相关规则,当应用出现异常的时候就会将用户的请求转发到降级用途的静态文件服务器上。

在整个规则配置过程中,发现了一些问题,就是在nginx上配置了相关error_page的跳转页面,发现后端应用异常的时候,预期中的nginx跳转规则并没有生效。

1
2
3
4
5
    error_page                    500 501 502 503 504 @shopstatic;
    location                      @shopstatic {
      access_log                  logs/shop-web.access.log       maintry;
      proxy_pass                  http://shopstaticservers;
    }

我们业务应用使用的是nginx+java容器的结构形式,nginx做反向代理和日志记录,当用户请求到达服务器时,先判断nginx配置的根目录下是否存在对应的静态文件,不存在的时候转发到后端的java容器server。我们在nginx中配置了error_page 异常跳转的规则,预期当后端java容器出现异常错误的时候,对应的请求会被nginx转发到我们静态降级的服务,但是实际上,当后端java容器出现异常或者过载的时候,nginx是直接吐出java容器后端的异常信息。

由于第一次配置这样奇特的nginx规则,搞不清楚是什么原因,在google上搜了半晌,由于搞不清楚状况,也描述不清楚,所以一直没有什么收获,后来终于用关键词error_page proxy搜索搞定了,一个老外回答了类似的问题,给了proxy_intercept_errors on;这个配置,自己试了下还真的ok了。

发现学会如何提问,才是自己要努力的方向。

nginx proxy 启用自定义错误页面:

语法:proxy_intercept_errors on | off;

默认值:

proxy_intercept_errors off;

上下文:http, server, location

当被代理的后端服务器的响应状态码大于等于300时,决定是否直接将响应发送给客户端,亦或将响应转发给nginx由error_page指令来处理。

原文:

syntax:proxy_intercept_errors on | off;

default:

proxy_intercept_errors off;

context:http, server, location

Determines whether proxied responses with codes greater than or equal to 300 should be passed to a client or be redirected to nginx for processing with the error_page directive.

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors

proxy_intercept_errors 为on 表示 nginx按照原response code 输出,后端是404,就是404.这个变量开启后,我们才能自定义错误页面。

语法:fastcgi_intercept_errors on | off;

默认值:

fastcgi_intercept_errors off;

上下文:http, server, location

当FastCGI后端服务器响应状态码大于等于300时,决定是否直接将响应发送给后端客户端,或者将响应转发给nginx由 error_page指令来处理。

原文:

syntax:fastcgi_intercept_errors on | off;

default:

fastcgi_intercept_errors off;

context:http, server, location

Determines whether FastCGI server responses with codes greater than or equal to 300 should be passed to a client or be redirected to nginx for processing with the error_page directive.

http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_intercept_errors

fastcgi_intercept_errors on表示接收fastcgi输出的http 1.0 response code,后端php可以输出header指示nginx输出什么错误页面。开启这个之后,我们才能在php里面自定义错误代码和页面。

必须明确的在error_page中指定处理方法使这个参数有效,如果没有适当的处理方法,nginx不会拦截一个错误,这个错误不会显示自己的默认页面,这里允许通过某些方法拦截错误。

本来以为这个参数应该大部分人都知道,但是发现很多人都不知道,所以专门再写出来。

原文地址:https://www.cnblogs.com/maohuidong/p/9425024.html