2017-03-04 170 views
2

當我在我的網站做維護和重新啓動服務器,有時NGINX返回502錯誤網關錯誤。同樣的事情有時在重負載下發生。這讓我的訪問者感到困惑,他們沒有意識到問題可能是暫時的。有什麼方法可以讓訪問者在網站返回時自動刷新頁面?自動刷新頁面上502錯誤網關錯誤

回答

1

您可以通過使用Javascript來檢查當前頁面的HTTP狀態碼並在服務器備份時刷新頁面(即返回200 OK狀態碼)。當許多用戶一次遇到502錯誤頁面時,爲避免錘擊服務器,我建議使用truncated binary exponential backoff算法。這意味着試之間的時間每次最多加倍,直到預設的最大值,從而降低您的服務器上的整體負載。

下面的代碼通過AJAX檢查當前頁面的HTTP狀態,直到它返回200 OK,在這種情況下,它將刷新頁面以獲取實時版本。如果遇到502,它將嘗試重試,從8秒間隔開始,然後是16,32,...,4096秒,然後以4096秒間隔(約68分鐘)無限制地重試。如果遇到除502200以外的任何代碼,則重試過程將自動中止(儘管如果需要,可以使用更多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; 
}