Nginx HTTP User_agent

來源:互聯網
上載者:User

標籤:blog   http   io   ar   使用   sp   java   strong   檔案   

假設我這裡有大量映像、CSS、javascript等靜態檔案,分別放在後端伺服器  192.168.1.5 和 192.168.1.6上,那麼我如何利用nginx的反向 Proxy功能將不同的 http_user_agent 請求發送到指定的伺服器上呢?如 "Mozilla" 轉寄到 192.168.1.5 ,MSIE  轉寄到 192.168.1.6 。


Nginx 網頁伺服器支援if條件運算式,由此來跳轉或者使用不同的組態變數。在本文中需要使用 $http_user_agent 變數,它標記了使用者瀏覽器的類別,版本以及作業系統的一些資訊

 

[html] view plaincopy 
  1. if ( condition ){  
  2.   do_something  
  3. }  
  4. if ( $http_user_agent = "wget" ){  
  5.    do_something  
  6. }  
  7. if ( $http_user_agent ~ MSIE ){  
  8.    return 403;  
  9. }  


if指令會就檢查後面運算式的值是否為真(true),如果為真,則執行後面大括弧中的內容。以下是一些條件運算式的比較方法:
1、變數的完整比較可以使用=或!=操作符
2、 部分匹配可以使用Regex來表示,~或~*
3、~表示區分大小寫
4、~*表示不區分大小寫(firefox與FireFox是一樣的)
5、!~與!~* 是取反操作,也就是不匹配的意思
6、檢查檔案是否存在使用 -f 或 !-f 操作符
7、檢查目錄是否存在使用-d或!-d操作符
8、檢查檔案,目錄或符號串連是否存在使用-e或!-e操作符
9、檢查檔案是否可執行使用-x或!-x操作符
10、Regex的部分匹配可以使用括弧,匹配的部分在後面可以用$1~$9變數代替,這些和apache一致。


例子:


編輯 /usr/local/nginx/conf/nginx.conf 檔案
#vi /usr/local/nginx/conf/nginx.conf
設定upstream伺服器:

 

 

[html] view plaincopy 
  1. upstream myproxybackend  {  
  2.        server 192.168.1.1;  
  3.        server 192.168.1.2;  
  4.        server 192.168.1.3;  
  5.        server 192.168.1.4;  
  6. }  
  7.    
  8. upstream msiebackend  {  
  9.        server 192.168.1.6;  
  10. }  
  11.    
  12. upstream mozillabackend  {  
  13.        server 192.168.1.5;  
  14. }  


更新虛擬機器主機設定檔

 

 

[html] view plaincopy 
  1. server {  
  2.       access_log  logs/access.log;  
  3.       error_log   logs/error.log;  
  4.       index       index.html;  
  5.       listen      202.54.1.5:80 default;  
  6.       root        /usr/local/nginx/html;  
  7.       server_name example.com www.example.com 0.example.com;  
  8.    
  9.      ## PROXY - Web  
  10.       location / {  
  11.         proxy_pass  http://myproxybackend;  
  12.         if ($http_user_agent ~ MSIE ) {  
  13.               proxy_pass  http://msiebackend;  
  14.         }  
  15.         if ($http_user_agent ~ Mozilla ) {  
  16.               proxy_pass  http://mozillabackend;  
  17.         }  
  18.    
  19.         proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;  
  20. # many more...  
  21. # many more...  
  22. }  


最後重啟/重新載入nginx

 

 

[html] view plaincopy 
    1. #/usr/local/nginx/sbin/nginx -s reload  

Nginx HTTP User_agent

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.