假如要将8080
端口上的请求转发至3000
端口。
以3000
端口为例,编写proxy_pass
有两种形式。
假设前端请求为 http://localhost:8080/get/test
。
我们暂且把 /get/test
称为请求部分。
不带 "/"
server {
listen 8080;
server_name localhost;
location /get {
proxy_pass http://localhost:3000;
}
#或者
location /get/ {
proxy_pass http://localhost:3000;
}
#结果都是 将http://localhost:8080/get/test转发去http://localhost:3000/get/test
}
proxy_pass:http://localhost:3000
无斜杆location
匹配到的部分也属于请求的部分。location
无论用/get
还是用/get/
只要匹配上之后都会将整个请求部分/get/test
加到proxy_pass
上。http://localhost:3000
+/get/test
等于请求http://localhost:3000/get/test
。
带 "/"
server {
listen 8080;
server_name localhost;
location /get {
# 结果是 将http://localhost:8080/get/test转发去http://localhost:3000//test,出错~
proxy_pass http://localhost:3000/;
}
#或者
location /get/ {
# 结果是 将http://localhost:8080/get/test转发去http://localhost:3000/test
proxy_pass http://localhost:3000/;
}
}
proxy_pass:http://localhost:3000/
。
有斜杆location
匹配到的部分只用于匹配,不属于请求部分,需要在请求部分将location
匹配到的部分剔除。location
用/get
则是http://localhost:3000/
+(/get/test
-/get
)等于请求http://localhost:3000//test
location
用/get/
则是http://localhost:3000/
+(/get/test
-/get/
)等于请求http://localhost:3000/test
"/" 后面还有路径信息
server {
listen 8080;
server_name localhost;
location /get {
# 结果是 将http://localhost:8080/get/test转发去http://localhost:3000/abc/test
proxy_pass http://localhost:3000/abc;
}
#或者
location /get/ {
# 结果是 将http://localhost:8080/get/test转发去http://localhost:3000/abctest,出错~
proxy_pass http://localhost:3000/abc;
}
}
proxy_pass:http://localhost:3000/abc
。
同有斜杆的规则,在请求部分剔除location后加在上面即可。location
用/get
则是http://localhost:3000/abc
+(/get/test
-/get
)等于请求http://localhost:3000/abc/testlocation
用/get/
则是http://localhost:3000/abc
+(/get/test
-/get/
)等于请求http://localhost:3000/abctest
总结
不带 /
时,可以理解为简单的全路径拼接,不作任何处理
带 /
时, proxy_pass
+ (原路径 - 匹配规则)
server {
listen 80;
server_name localhost; # http://localhost/wddd01/xxx -> http://localhost:8080/wddd01/xxx
location /wddd01/ {
proxy_pass http://localhost:8080;
}
# http://localhost/wddd02/xxx -> http://localhost:8080/xxx
location /wddd02/ {
proxy_pass http://localhost:8080/;
}
# http://localhost/wddd03/xxx -> http://localhost:8080/wddd03*/xxx
location /wddd03 {
proxy_pass http://localhost:8080;
}
# http://localhost/wddd04/xxx -> http://localhost:8080//xxx,请注意这里的双斜线,好好分析一下。
location /wddd04 {
proxy_pass http://localhost:8080/;
}
# http://localhost/wddd05/xxx -> http://localhost:8080/hahaxxx,请注意这里的haha和xxx之间没有斜杠,分析一下原因。
location /wddd05/ {
proxy_pass http://localhost:8080/haha;
}
# http://localhost/api6/xxx -> http://localhost:8080/haha/xxx
location /wddd06/ {
proxy_pass http://localhost:8080/haha/;
}
# http://localhost/wddd07/xxx -> http://localhost:8080/haha/xxx
location /wddd07 {
proxy_pass http://localhost:8080/haha;
}
# http://localhost/wddd08/xxx -> http://localhost:8080/haha//xxx,请注意这里的双斜杠。
location /wddd08 {
proxy_pass http://localhost:8080/haha/;
}
}