終於有時間對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,就是用來展示停機維護頁的,把這行的注釋刪掉,則所有請求都將被轉到上面的停機維護頁。
如果采用的是 nginx + tomcat 的模式,還需要在 nginx 的配置文件中添加這行代碼,作用是使用 nginx 來攔截容器的 404 等錯誤:
proxy_intercept_errors on;
如果不加這行,還是會顯示 tomcat 默認的404頁面。
