標籤: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
- if ( condition ){
- do_something
- }
- if ( $http_user_agent = "wget" ){
- do_something
- }
- if ( $http_user_agent ~ MSIE ){
- return 403;
- }
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
- upstream myproxybackend {
- server 192.168.1.1;
- server 192.168.1.2;
- server 192.168.1.3;
- server 192.168.1.4;
- }
-
- upstream msiebackend {
- server 192.168.1.6;
- }
-
- upstream mozillabackend {
- server 192.168.1.5;
- }
更新虛擬機器主機設定檔
[html] view plaincopy
- server {
- access_log logs/access.log;
- error_log logs/error.log;
- index index.html;
- listen 202.54.1.5:80 default;
- root /usr/local/nginx/html;
- server_name example.com www.example.com 0.example.com;
-
- ## PROXY - Web
- location / {
- proxy_pass http://myproxybackend;
- if ($http_user_agent ~ MSIE ) {
- proxy_pass http://msiebackend;
- }
- if ($http_user_agent ~ Mozilla ) {
- proxy_pass http://mozillabackend;
- }
-
- proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
- # many more...
- # many more...
- }
最後重啟/重新載入nginx
[html] view plaincopy
- #/usr/local/nginx/sbin/nginx -s reload
Nginx HTTP User_agent