Nginx不服务我的error_page



我有一个Sinatra应用托管独角兽,和nginx在它的前面。当Sinatra应用程序出错(返回500)时,我希望提供一个静态页面,而不是默认的"内部服务器错误"。我有以下nginx配置:

server {
  listen 80 default;
  server_name *.example.com;
  root /home/deploy/www-frontend/current/public;
  location / {
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_connect_timeout 5;
    proxy_read_timeout 240;
    proxy_pass http://127.0.0.1:4701/;
  }
  error_page 500 502 503 504 /50x.html;
}

error_page指令在那里,我已经sudo为www-data (Ubuntu)并验证我可以cat文件,因此这不是权限问题。使用上述配置文件和service nginx reload,我收到的错误页面仍然是相同的"内部服务器错误"。

我的错误是什么?

error_page处理nginx生成的错误。默认情况下,nginx将返回代理服务器返回的任何内容,而不管http状态码。

你要找的是proxy_intercept_errors

这个指令决定nginx是否会拦截HTTP响应状态码为400及以上

默认情况下,所有响应将按原样从代理服务器发送。

如果你将这个设置为on,那么nginx将拦截状态码由error_page指令显式处理。状态响应不匹配error_page指令的代码将按原样发送

可以设置proxy_intercept_errors

location /some/location {
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_connect_timeout 5;
    proxy_read_timeout 240;
    proxy_pass http://127.0.0.1:4701/;
    proxy_intercept_errors on; # see http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors
    error_page 400 500 404 ... other statuses ... =200 /your/path/for/custom/errors;
}

你可以设置200个你需要的状态

使用FastCGI作为上游的用户需要打开这个参数

fastcgi_intercept_errors on;

对于我的PHP应用程序,我使用它在我的上游配置块

 location ~ .php$ { ## Execute PHP scripts
    fastcgi_pass   php-upstream; 
    fastcgi_intercept_errors on;
    error_page 500 /500.html;
 }

正如Stephen在此响应中提到的,使用proxy_intercept_errors on;可以工作。虽然在我的情况下,正如在这个答案中看到的,使用uwsgi_intercept_errors on;做到了这一点…

最新更新