nginx根據不同的訪問地址路由到不同的服務
阿新 • • 發佈:2022-03-27
nginx根據不同的訪問地址路由到不同的服務
1 目標描述
當訪問的瀏覽器的url不一樣時,請求會路由到不同的伺服器上;
目標如下:
- 輸入以web開頭的地址路由到web相關的api上;
- 輸入以phone開頭的地址路由到phone相關的api上;
結果展示
訪問http://127.0.0.1:9999/phone/app/a.html,瀏覽器返回的結果為:
server-phone
訪問http://127.0.0.1:9999/web/app/a.html,瀏覽器返回的結果為:
server-web
2 環境準備
- 配置好兩個tomcat,埠號分別為8080,8081;
- 分別在兩個tomcat的webapp目錄中分別建立app資料夾;
- 分別兩個伺服器中的app資料夾內編寫a.html檔案;
- 8081伺服器中a.html內容為
server-web;
80801中a.html的內容為server-phone
; - 分別測試
http://127.0.0.1:8080/app/a.html
和http://127.0.0.1:8081/app/a.html
,測試返回結果是否正常;
3 nginx配置
在server模組配置如下
server { listen 9999; # 監聽的埠號 server_name 192.168.0.103; # nginx所在的伺服器ip # 訪問web開頭的url路由的服務地址 location /web { proxy_pass http://127.0.0.1:8080/; } # 訪問phone開頭的url路由的服務地址 location /phone { proxy_pass http://127.0.0.1:8081/; } }
啟動nginx
./nginx
訪問url測試是否配置成功,測試url如下:
http://127.0.0.1:9999/web/app/a.html
http://127.0.0.1:9999/phone/app/a.html
4 注意事項
location中後面如果不是單純的/
情況下,比如location /web
,這個時候proxy_pass配置的url一定要以/
結尾;否則則會訪問不到對應的server服務;
錯誤樣例
proxy_pass http://127.0.0.1:8081;
正確樣例
proxy_pass http://127.0.0.1:8081/;