天天看點

Nginx中proxy_pass的斜杠(/)問題

一、概述

Nginx的官網将proxy_pass分為兩種類型:
一種是隻包含IP和端口号的(連端口之後的/也沒有,這裡要特别注意),比如proxy_pass http://localhost:8080,這種方式稱為不帶
URI方式;
另一種是在端口号之後有其他路徑的,包含了隻有單個/的如proxy_pass http://localhost:8080/,以及其他路徑,比如proxy_pass 
http://localhost:8080/abc。
也即:proxy_pass http://localhost:8080和proxy_pass http://localhost:8080/(多了末尾的/)是不同的的處理方式,
而proxy_pass http://localhost:8080/和proxy_pass http://localhost:8080/abc是相同的處理方式。

如果proxy_pass末尾有斜杠/,proxy_pass不拼接location的路徑
如果proxy_pass末尾無斜杠/,proxy_pass會拼接location的路徑      

二、實驗

server {
   listen       80;
   server_name  localhost;
   location /api1/ {
           proxy_pass http://localhost:8080;
        }
   # http://localhost/api1/xxx -> http://localhost:8080/api1/xxx

   location /api2/ {
           proxy_pass http://localhost:8080/;
        }
   # http://localhost/api2/xxx -> http://localhost:8080/xxx

   location /api3 {
           proxy_pass http://localhost:8080;
        }
   # http://localhost/api3/xxx -> http://localhost:8080/api3/xxx

   location /api4 {
           proxy_pass http://localhost:8080/;
        }
   # http://localhost/api4/xxx -> http://localhost:8080//xxx,請注意這裡的雙斜線

   location /api5/ {
           proxy_pass http://localhost:8080/haha;
        }
   # http://localhost/api5/xxx -> http://localhost:8080/hahaxxx,請注意這裡的haha和xxx之間沒有斜杠

   location /api6/ {
           proxy_pass http://localhost:8080/haha/;
        }
   # http://localhost/api6/xxx -> http://localhost:8080/haha/xxx

   location /api7 {
           proxy_pass http://localhost:8080/haha;
        }
   # http://localhost/api7/xxx -> http://localhost:8080/haha/xxx

   location /api8 {
           proxy_pass http://localhost:8080/haha/;
        }
  # http://localhost/api8/xxx -> http://localhost:8080/haha//xxx,請注意這裡的雙斜杠。
}