Nginx 代理中使用斜杠的区别
编辑
              
              295
            
            
          2023-09-06
          Nginx 代理中使用斜杠的区别
代理地址是:http://127.0.0.1:8000
1、代理地址不加斜杠
# 请求路径为:http://127.0.0.1:8080/api/getInfo  
# 实际代理为:http://127.0.0.1:8000/api/getInfo
location ^~/api/ {
  proxy_pass http://127.0.0.1:8000;
  proxy_set_header Host $http_host; 
  proxy_set_header X-Real-IP $remote_addr; 
}
# 请求路径为:http://127.0.0.1:8080/api/getInfo
# 实际指向为:http://127.0.0.1:8000/api/getInfo
location ^~/api {
  proxy_pass http://127.0.0.1:8000;
  proxy_set_header Host $http_host; 
  proxy_set_header X-Real-IP $remote_addr; 
}
location定位的路径设置,是否带斜杠,没有关系。
2、代理地址 + 斜杠
# 请求路径为:http://127.0.0.1:8080/api/getInfo
# 实际代理为:http://127.0.0.1:8000/getInfo
location ^~/api/ {
  proxy_pass http://127.0.0.1:8000/;
  proxy_set_header Host $http_host; 
  proxy_set_header X-Real-IP $remote_addr; 
}
# 请求路径为:http://127.0.0.1:8080/api/getInfo
# 实际代理为:http://127.0.0.1:8000//getInfo
location ^~/api {
  proxy_pass http://127.0.0.1:8000/;
  proxy_set_header Host $http_host; 
  proxy_set_header X-Real-IP $remote_addr; 
}
如果代理地址加了斜杠,不管location是否加斜杠,api路径都省略了。
3、代理地址 + 后缀
# 请求路径为:http://127.0.0.1:8080/api/getInfo
# 实际代理为:http://127.0.0.1:8000/wxgetInfo
location ^~/api/ {
  proxy_pass http://127.0.0.1:8000/wx;
  proxy_set_header Host $http_host; 
  proxy_set_header X-Real-IP $remote_addr; 
}
# 请求路径为:http://127.0.0.1:8080/api/getInfo
# 实际代理为:http://127.0.0.1:8000/wx/getInfo
location ^~/api {
  proxy_pass http://127.0.0.1:8000/wx;
  proxy_set_header Host $http_host; 
  proxy_set_header X-Real-IP $remote_addr; 
}
如果location带斜杠,会省略url中的斜杠。
4、代理地址 + 后缀 + 斜杠
# 请求路径为:http://127.0.0.1:8080/api/getInfo
# 实际代理为:http://127.0.0.1:8000/wx/getInfo
location ^~/api/ {
  proxy_pass http://127.0.0.1:8000/wx/;
  proxy_set_header Host $http_host; 
  proxy_set_header X-Real-IP $remote_addr; 
}
# 请求路径为:http://127.0.0.1:8080/api/getInfo
# 实际代理为:http://127.0.0.1:8000/wx/getInfo
location ^~/api {
  proxy_pass http://127.0.0.1:8000/wx/;
  proxy_set_header Host $http_host; 
  proxy_set_header X-Real-IP $remote_addr; 
}
如果location带斜杠,会省略url中的斜杠。
- 看起来很简单,但是实际中有可能搞错,出现一些莫名的问题。
- 7
- 0
- 
              
              
  分享