nginx 重定向到系統維護頁面


 

上周末兄弟項目准備擴展服務器以便提供更好的服務,兄弟項目有一些功能是實時提供到我這邊的,需要我這邊暫時把對應系統功能屏蔽,因為使用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后面必須要有一個空格!!!!,太坑了,網上那些介紹nginx if的文章都沒有提到這么重要的信息。。。

 

 

 

感謝資料:

if后必須有空格:https://blog.csdn.net/palet/article/details/103394236

nginx中return和rewrite:https://blog.csdn.net/u010982507/article/details/104025717

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM