侧边栏壁纸
博主头像
王旭阳个人博客博主等级

工欲善其事,必先利其器

  • 累计撰写 119 篇文章
  • 累计创建 28 个标签
  • 累计收到 23 条评论

目 录CONTENT

文章目录

Nginx 代理中使用斜杠的区别

wxy
wxy
2023-09-06 / 0 评论 / 4 点赞 / 117 阅读 / 4093 字
温馨提示:
本文最后更新于 2023-12-19,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

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中的斜杠。

  • 看起来很简单,但是实际中有可能搞错,出现一些莫名的问题。
4

评论区