1. 程式人生 > 其它 >Nginx配置轉發

Nginx配置轉發

 需求:

同一域名+不同字尾轉發到

不同伺服器ip+埠的webapi介面(198.122.133.4:800,199.122.133.5:800,197.122.133.6:800)

 

說明:

nginx location proxy_pass 後面的url 加與不加/的區別
在nginx中配置proxy_pass時,當在後面的url加上了/,相當於是絕對根路徑,則nginx不會把location中匹配的路徑部分代理走;如果沒有/,則會把匹配的路徑部分也給代理走。
 

首先是location進行的是模糊匹配

1)沒有“/”時,location /abc/def可以匹配/abc/defghi請求,也可以匹配/abc/def/ghi等
2)而有“/”時,location /abc/def/不能匹配/abc/defghi請求,只能匹配/abc/def/anything這樣的請求


 
 server {
        listen       80;
        server_name  www.baidu.com;
        location /test1/{  
            proxy_pass http://198.122.133.4:800/;   #轉發請求的地址 
        } 
        location /test2/{  
            proxy_pass http://199.122.133.5:800/;   #轉發請求的地址 
        } 
        location /test3/{  
            proxy_pass http:
//196.122.133.6:800/; #轉發請求的地址 }

 

訪問 

www.baidu.com/test1/ 呼叫的是 http://198.122.133.4:800/

注意 四種情況
第一種
location  /test/ {

    proxy_pass http://127.0.0.1:5000/;

}

結論:會被代理到http://127.0.0.1:5000/這個url

 

 

 第二種(相對於第一種,最後少一個 /)

location  /test/ {
     proxy_pass http://127.0.0.1:5000; 
}

結論:會被代理到http://127.0.0.1:5000/test/api這個url

第三種
location  /test/ {

proxy_pass http:
//127.0.0.1:5000/test/; }

結論:會被代理到http://127.0.0.1:5000/test/api這個url。

第四種(相對於第三種,最後少一個 / ):
location  /test/ {

     proxy_pass http://127.0.0.1:5000/test;

}

結論:會被代理到http://127.0.0.1:5000/testapi這個url

 

最終配置

location /sys/{                                             //轉發路徑
            proxy_set_header Host $http_host;               
            proxy_set_header X-Real-Ip $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://192.168.2.45:8080/;           //後端地址

        }

 

 

參考 http://events.jianshu.io/p/c9c29515b706