Nginx的location路径与proxy_pass匹配规则

路径替换

  1. 配置proxy_pass时,可以实现URL路径的部分替换。
  2. proxy_pass的目标地址,默认不带/,表示只代理域名(ip+端口),path和query部分不会变(把请求的path和query拼接到proxy_pass目标域名之后作为代理的URL)
  3. 如果在目标地址端口后有‘/’或者‘/xx/yy’等目录,则表示把path中location匹配成功的部分剪切掉之后再拼接到proxy_pass目标地址后面

比如请求 /a/b.html

location /a {
    proxy_pass http://server;
}

实际代理的目标url是http://server/a/b.html (把/a/b.html拼接到http://server之后)

location /a/ {
    proxy_pass http://server/;
}

总结

当访问地址是 http://127.0.0.1/api/user/list

  1. 若proxy_pass代理地址端口后无任何字符,则转发后地址为:代理地址+访问的path
locationproxy_pass代理路径
/api/http://server:8080http://server:8080/api/user/list
/api/http://server:8080/http://server:8080/user/list
/apihttp://server:8080http://server:8080/api/user/list
/apihttp://server:8080/http://server:8080//user/list
  1. 若proxy_pass代理地址端口后有目录(包括"/"),则转发后地址为:代理地址+访问的path去除location匹配的路径
locationproxy_pass代理路径
/api/http://server:8080/gwhttp://server:8080/gwuser/list
/api/http://server:8080/gw/http://server:8080/gw/user/list
/apihttp://server:8080/gwhttp://server:8080/gw/user/list
/apihttp://server:8080/gw/http://server:8080/gw//user/list

注意:location后斜杆与proxy_pass后斜杆"/"问题,最好要么两者都加斜杆,要么都不加

以服务地址http://127.0.0.1:5053/api/test/list进行说明,访问地址是http://127.0.0.1/api/test/list。location后斜杆与proxy_pass后斜杆问题如下:

  1. location、proxy_pass都不加斜杠,实际代理地址:http://127.0.0.1:5053/api/test/list,正确的
location /api {
  proxy_pass http://127.0.0.1:5053;
}
  1. location加斜杠,proxy_pass不加斜杠,实际代理地址:http://127.0.0.1:5053/api/test/list,正确的
location /api/ {
  proxy_pass http://127.0.0.1:5053;
}
  1. location不加斜杠,proxy_pass加斜杠,实际代理地址:http://127.0.0.1:5053//test/list,错误的,也出现了双斜杠
location /api {
  proxy_pass http://127.0.0.1:5053/;
}
  1. location、proxy_pass都加斜杠,实际代理地址:http://127.0.0.1:5053/test/list,错误的
location /api/ {
  proxy_pass http://127.0.0.1:5053/;
}
  1. location不加斜杠,proxy_pass加"api",实际代理地址:http://127.0.0.1:5053/api/test/list,正确的
location /api {
  proxy_pass http://127.0.0.1:5053/api;
}
  1. location加斜杠,proxy_pass加"api",实际代理地址:http://127.0.0.1:5053/apitest/list,错误的,少了一个斜杆
location /api/ {
  proxy_pass http://127.0.0.1:5053/api;
}
  1. location不加斜杠,proxy_pass加"api/",实际代理地址:http://127.0.0.1:5053/api//test/list,出现双斜杠问题,后端在认证请求时会校
    验失败
location /api {
  proxy_pass http://127.0.0.1:5053/api/;
}
  1. location加斜杠,proxy_pass加"api/",实际代理地址:http://127.0.0.1:5053/api/test/list,正确的
location /api/ {
  proxy_pass http://127.0.0.1:5053/api/;
}
  • 25
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kse_music

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值