介紹如何讓 Nginx 網頁伺服器快速切換為維護模式,顯示「網站維護中」訊息頁面。
自訂 HTTP 503 網站維護訊息網頁
HTTP 503 代表的是目前伺服器暫時不能處理連線的請求(Service Unavailable),如果網站處於維護狀態(或是出現某些問題),暫時不對外開放的時候,就適合傳回 HTTP 503 這一個狀態碼,告知使用者網站正在維護中,請稍後再來。
在 Nginx 伺服器中,我們可以自訂 HTTP 503 的頁面,讓使用者更清楚伺服器的維護狀態,例如告知預計開放時間等。
首先建立一張 html 網頁,內容就是要告知使用者的網站維護資訊,類似像這樣:
<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>網站維護中</title>
<style>
body {
text-align: center;
padding-top: 50px;
}
</style>
</head>
<body>
<h1 style="color: #CC0000;">網站維護中</h1>
<h2>預計開放時間:2020/06/24 12:00 PM</h2>
</body>
</html>
將這張 html 網頁儲存為 under_construction.html,然後在網頁目錄中找個適合的位置放置,因為只有一個檔案,通常就放在網頁的根目錄即可,例如 /var/www/html 目錄中。
接著修改 Nginx 伺服器的設定檔,在 server 區塊中自訂 HTTP 503 頁面,同時設定自動判斷 under_construction.html 這一個檔案是否存在,如果發現該檔案的時候,就自動傳回 HTTP 503:
server {
# ...
# 若 under_construction.html 存在,則傳回 HTTP 503
if (-f $document_root/under_construction.html) {
return 503;
}
# 將原本的 503 拿掉
#error_page 500 502 503 504 /50x.html;
# location = /50x.html {
#}
error_page 500 502 504 /50x.html;
location = /50x.html {
}
# 自訂 HTTP 503 頁面
error_page 503 @maintenance;
location @maintenance {
rewrite ^(.*)$ /under_construction.html break;
}
}
修改完成之後,檢查 Nginx 設定檔語法是否正確,然後重新啟動 Nginx 伺服器:
# 檢查 Nginx 設定檔是否正確
sudo nginx -t
# 重新啟動 Nginx 伺服器
systemctl restart nginx
在這樣的設定之下,只要 /under_construction.html 這一個網頁檔案存在,伺服器就會自動傳回 HTTP 503,並顯示這一張網頁的內容,而當伺服器要正常上線服務時,只要把 /under_construction.html 這個網頁檔案改成其他名稱(或移至別處),就可以讓 Nginx 伺服器恢復正常的運作。
開放內部開發者瀏覽
如果希望網站在處於維護狀態時,內部的開發者還是可以正常瀏覽網頁內容,可以將設定改成以下這種寫法:
server {
# ...
# 檢查是否為內部開發者 IP
set $internalIP 0;
if ($remote_addr = "12.34.56.78") { # 第一個開發者
set $internalIP 1;
}
if ($remote_addr = "21.43.65.87") { # 第二個開發者
set $internalIP 1;
}
# 檢查 under_construction.html 是否存在
if (-f $document_root/under_construction.html) {
# 結合 under_construction.html 與 IP 資訊
set $underConstruction "${internalIP}1";
}
# 若 under_construction.html 存在,且來源 IP 並非內部開發者,
# 則傳回 HTTP 503
if ($underConstruction = "01") {
return 503;
}
# 將原本的 503 拿掉
#error_page 500 502 503 504 /50x.html;
# location = /50x.html {
#}
error_page 500 502 504 /50x.html;
location = /50x.html {
}
# 自訂 HTTP 503 頁面
error_page 503 @maintenance;
location @maintenance {
rewrite ^(.*)$ /under_construction.html break;
}
}
在這個設定中,會逐一檢查所有開發者的 IP,若發現是開發者的 IP,就會顯示正常的網頁,而普通外部的使用者則會看到 HTTP 503 頁面。
維護中插圖
以下有兩張網頁維護中的插圖,很適合用於 HTTP 503 頁面,不過使用前要先用 DATA URI 的方式,先將圖片轉為 base64 編碼後再嵌入網頁中。


