自动刷新页面出现502 Bad Gateway错误
·
问题:自动刷新页面出现502 Bad Gateway错误
当我在我的站点上进行维护并重新启动服务器时,有时 NGINX 会返回 502 Bad Gateway 错误。同样的事情有时会在重负载下发生。这让我的访客感到困惑,他们没有意识到这个问题可能是暂时的。有什么方法可以让访问者在网站返回时自动刷新页面?
解答
您可以通过使用 Javascript 检查当前页面的 HTTP 状态码,并在服务器备份时刷新页面(即返回200 OK状态码)来实现这一点。当很多用户同时遇到502错误页面时,为了避免锤击服务器,我建议使用截断二进制指数退避算法。这意味着每次重试之间的时间都会加倍,直到达到预设的最大值,这会降低服务器上的整体负载。
下面的代码通过 AJAX 检查当前页面的 HTTP 状态,直到它返回200 OK,在这种情况下,它将刷新页面以获取实时版本。如果遇到502,它将尝试重试,从 8 秒间隔开始,然后 16、32、...、4096 秒,然后以 4096 秒间隔(约 68 分钟)无限次重试。如果遇到除502或200之外的任何代码,则重试过程会静默中止(尽管如果需要,您可以使用更多case语句来更改它)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Currently unavailable</title>
</head>
<body>
<h1>Site currently unavailable (code 502)</h1>
<p>This page will refresh when the site is back.</p>
<noscript>Your browser doesn’t support javascript. Please try refreshing the page manually every few minutes.</noscript>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
/* Set starting and maximum retry times in seconds */
var retry_current = 8, // first refresh at 8 seconds
retry_max = 4096, // refresh time truncated at about 68 minutes
check_response = function() {
$.ajax(
{
url: window.location.href,
type: "HEAD",
complete: function (jqXHR) {
switch (jqXHR.status) {
case 200:
window.location.reload(true);
break;
case 502:
if(retry_current < retry_max) {
retry_current *= 2;
}
setTimeout(check_response, retry_current * 1000);
}
}
});
};
setTimeout(check_response, retry_current * 1000);
</script>
</body>
</html>
如果您使用的是 nginx,则可以将以下内容添加到配置文件中以使用该页面:
error_page 502 /502.html;
location = /502.html {
alias /path/to/502.html;
}
更多推荐

所有评论(0)