是否可以更改在nginx中关闭proxy_pass网关时返回的HTTP状态代码?

时间:2011-11-23 05:37:10

标签: http proxy nginx

出于搜索引擎优化的目的,我们希望在由于某种原因nginx后面的后端机器出现故障时更改返回的HTTP状态代码。

我们想将此更改为“503 Service Unavailable”。除了向Google / Bing提供一个Retry-After标头之外,还应该在X秒内重试该请求。

这可以通过nginx吗?

我不是在谈论自定义错误页面,而是在标题中返回的状态代码。

2 个答案:

答案 0 :(得分:33)

我认为你 必须设置一个特定的错误页面,但如果你这样做,你可以实现你想要的。试试这个:

location / {
    proxy_pass http://backend;
    proxy_intercept_errors on;
    error_page 502 503 504 =503 @proxyisdown; # always reply with 503
}

location @proxyisdown {
    add_header Retry-After 500 always;
    index my_pretty_error_page.html; 
}

如果你以这种方式工作,你应该能够返回503(=503指令的error_page部分)和重试后标题,这样可以让访问者获得良好的收益格式化“哎呀,我们目前遇到问题,请在几分钟后再试”页面而不是空白“503你真的不知道这意味着什么”页面。 :)

答案 1 :(得分:2)

将错误页面命名为/500.html并:

error_page 400 404 500 502 504 =503 /500.html;

# Optional if your public root is set above and the same for error pages,
# I sometimes please them outside the app, which is why I'm including it.
location /500.html {
  root /path/to/public;
}

应该也能正常工作,对我来说似乎有点简单。注意:它也不支持Header。