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
是相同的處理方式。
對於不帶 URI 方式,nginx 將會保留 location 中路徑部分,比如:
location /api1/ {
proxy_pass http://localhost:8080;
}
在訪問 http://localhost/api1/xxx
時,會代理到 http://localhost:8080/api1/xxx
對於帶 URI 方式,nginx 將使用諸如 alias 的替換方式對 URL 進行替換,並且這種替換隻是字面上的替換,比如:
location /api2/ {
proxy_pass http://localhost:8080/;
}
當訪問 http://localhost/api2/xxx
時, http://localhost/api2/
(注意最後的 /
)被替換成了 http://localhost:8080/
,然後再加上剩下的 xxx
,於是變成了 http://localhost:8080/xxx
。
又比如:
location /api5/ {
proxy_pass http://localhost:8080/haha;
}
當訪問 http://localhost/api5/xxx
時, http://localhost/api5/
被替換成了 http://localhost:8080/haha
,請注意這裏 haha
後面沒有 /
,然後再加上剩下的 xxx
,即 http://localhost:8080/haha
+ xxx
= http://localhost:8080/hahaxxx
,奇怪吧。
總結一下:
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,請注意這裏的雙斜槓。
}