需求:
同一域名+不同后綴轉發到
不同服務器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中匹配的路徑部分代理走;如果沒有/,則會把匹配的路徑部分也給代理走。
在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