關於nginx自定義錯誤頁及停機維護頁的配置筆記
阿新 • • 發佈:2022-03-11
終於有時間對nginx的錯誤頁和停機維護頁進行簡單的優化和配置,看起來比原始的提示資訊友好多了。
首先,在nginx的安裝目錄建立相關的配置檔案:errpage.conf
error_page 403 /403.html; error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location /lost { root .; } location = /403.html { root lost; } location = /404.html { root lost; } location = /50x.html { root lost; } location = /off.html { root lost; }
這個檔案裡配置了 3 個錯誤狀態的內部跳轉,其中:
- 403:表示無法列出目錄明細;
- 404:表示目標檔案不存在;
- 50x:表示服務端的錯誤,簡單起見統一使用一個頁面即可。
另外,還配置了 5 個路徑匹配模板,其中 3 個用於響應上面的錯誤頁,另外 2 個:
- /lost:用於訪問各錯誤頁中的靜態資源,包括圖片、css、js等;
- /off.html:用於響應停機維護頁
配置檔案準備好之後,下面就需要對各頁面進行實現了,完成之後的目錄結構:
看一下off頁的執行效果:
需要注意的是,在設計頁面時,為了方便預覽,頁面內的靜態資源可直接使用相對路徑下的檔名,但設計完成後,部署到nginx時,都需要使用 /lost/xxx.png 模式的路徑,因為所有的靜態資源都被配置到了 /lost 目錄下。
另外,lost目錄的部署位置:
- windows:預設是 nginx 的根目錄,就是nginx.exe檔案所在的目錄;
- linux:預設是 /usr/share/nginx 目錄下。
最後,在nginx的主配置檔案中引入上面的配置檔案:
#主服務 server { listen 80; server_name localhost; location / { #try_files '' /off.html; #proxy_pass http://www.baidu.com; root html; index index.html index.htm default.html default.htm; expires 3d; } include errpage.conf; }
已被註釋掉的 try_files,就是用來展示停機維護頁的,把這行的註釋刪掉,則所有請求都將被轉到上面的停機維護頁。