上周末兄弟項目準備擴展服務器以便提供更好的服務,兄弟項目有一些功能是實時提供到我這邊的,需要我這邊暫時把對應系統功能屏蔽,因為使用nginx,所以可以直接配置nginx重定向到固定系統維護頁面。
nginx重定向其實很簡單,用return或rewrite關鍵字均可,因為重定向后直接跳轉到靜態頁面,不需要后續操作和記錄,所以直接301永久重定向。
其中重定向既可以在server中配置,也可以在具體的location中配置,下面分別簡單介紹。
在server中配置:
http {
server{
listen 80;
server_name A.com;
# 以下return 或 rewrite 選擇其中一個就行。其中upgrade.html 是自己寫的提示頁面
return 301 http://B.com/upgrade.html;
# rewrite ^/(.*)$ http://B.com/upgrade.html permanent;
location / { # 此處省略后面配置內容 } } }
或者在location中配置:
http {
server{
listen 80;
server_name A.com;
location / {
rewrite ^/(.*)$ http://B.com/upgrade.html permanent;
# 此處省略后面配置內容 } } }
從以上實例看出,return用301參數重定向,rewrite用permanent(當然還可以用break,last,區別的話自己查資料)。
不知道你們有沒有發現,以上兩個例子中,都是用 A.com去重定向到 B.com ,我試過,用A.com直接重定向到A.com/upgrade.html,會報錯重復次數太多,也就是進入死循環。在同時管理多個域名是可以配置用A重定向B,但是如果只有一個域名A那怎么弄呢?
這時候就用到if條件判斷了,此處我們以在server中配置為例說明:
http {
server{
listen 80;
server_name A.com;
# 注意 if 后面必須有一個空格!!!
if ($request_uri !~ "/upgrade.html$") {
return 301 http://A.com/upgrade.html;
}
location / {
# 此處省略后面配置內容
}
}
}
以上實例說明,當訪問路徑不包含 /upgrade.html時就重定向到upgrade.html,此時能夠重定向,不會再有重復次數太多的提示,但有另一個問題,就是upgrade.html中的圖片無法顯示了,暫時沒時間去研究如何避免圖片被重定向了,后面有時間再補充。
測試if條件的時候,遇到一個特別坑的事,就是添加if后重啟nginx報錯:
Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.
輸入systemctl status nginx.service可查看錯誤信息,其中nginx: [emerg] unknown directive "if($request_uri"錯誤查找到答案,原來是if后面必須要有一個空格!!!!,太坑了,網上那些介紹nginxif的文章都沒有提到這么重要的信息。。。
感謝資料:
if后必須有空格:https://blog.csdn.net/palet/article/details/103394236
nginx中return和rewrite:https://blog.csdn.net/u010982507/article/details/104025717
知識點補充
配置nginx輸入任何地址都跳轉至維護頁面
筆記一下:配置nginx輸入任何地址都跳轉至維護頁面
server {
listen 80;
root /xxx/xxx/src;
index index.html index.htm;
server_name test.xxx.com;
set $flag 0;
if ($request_uri !~ "(/static/.*)$"){
set $flag "${flag}1";
}
if ($request_uri !~ "/502.html$" ){
set $flag "${flag}2";
}
if ($flag = "012") {
rewrite ^(.*) http://test.xxx.com/502.html permanent;
}
location /{
...
以上就是nginx 重定向到系統維護頁面的詳細內容,更多關于nginx重定向維護頁面的資料請關注腳本之家其它相關文章!