本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前言
nginx的代理的路径是否有时候会让你摸不着头脑?介绍nginx配置文件中proxy_pass路径后带/与不带/的区别,只有掌握了这个,才能不被nginx的代理的路径弄混乱,对于nginx的基础使用大有帮助。
问题背景
假如要将8080端口上的请求转发至3000端口。
以3000端口为例,编写proxy_pass
有两种形式。
- 无斜杆:
http://localhost:3000
- 有斜杆:
http://localhost:3000/
假设前端请求为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/test
location用/get/
则是http://localhost:3000/abc
+(/get/test
-/get/
)等于请求http://localhost:3000/abctest
尾言
如果觉得文章对你有帮助的话,欢迎点赞收藏哦,有什么错误或者意见建议也可以留言,感谢~