Nginx的location配置和proxy_pass配置规则理解

1. Nginx配置规则

  1. location=/uri

=号开头表示精确匹配,只有完全匹配才能生效。

  1. location ^~/uri

^~开头对URL路径进行前缀匹配,并且在正则之前

  1. location ~pattern

~开头表示区分大小写的正则匹配

  1. location /uri

不带任何修饰符,也表示前缀匹配,但是在正则匹配之后,如果没有正则命中,命中最长的规则

  1. location /

通用匹配,任何未匹配到其他location的请求都会被匹配到,相当于switch中的default

1.1 优先级总结

  1. 精确匹配>带有修饰符的前缀匹配>正则匹配>不带任何修饰符的前缀匹配>通用匹配

2. location是否以/结尾

  1. 在nginx中location进行的是模糊匹配

1、没有“/”结尾时,location /abc/def可以匹配/abc/defghi请求,也可以匹配/abc/def/ghi等
2、而有“/”结尾时,location /abc/def/不能匹配/abc/defghi请求,只能匹配/abc/def/anything这样的请求

  1. 总结:

“/” 就像一个标识符,location的模糊匹配只能匹配标识符后面的内容

3. proxy_pass配置规则

  1. 配置proxy_pass时,当在后面的url加上/,相当于是绝对路径,则Nginx不会把location中匹配的路径部分加入到代理uri。
  2. 如果配置proxy_pass时,后面没有/,Nginx则会把匹配的路径部分加入代理URI

3.1 location的六种情况

  1. 情景1:proxy_pass后有/ ,表绝对路径,不把匹配部分加入最终代理路径(location 和proxy_pass结尾一致)
#访问地址:http://127.0.0.1:8081/WCP.Service/wcp/modeladapter/download/asc.shtml
#最终代理:http://127.0.0.1:13082/modeladapter/download/asc.shtml
location /WCP.Service/wcp/modeladapter/download/ {
  proxy_pass   http://127.0.0.1:13082/modeladapter/download/;
}


#访问地址:http://localhost:8081/model/asc.shtml
#最终代理:http://127.0.0.1:8082/model/asc.shtml
location /model/ {
  proxy_pass   http://127.0.0.1:8082/model/;
}
  1. 情景2:proxy_pass后有/ ,表绝对路径,不把匹配部分加入最终代理路径(location 和proxy_pass结尾不一致)
#访问地址:http://localhost:8081/model/asc.shtml
#最终代理:http://127.0.0.1:8082/asc.shtml
location /model/ {
  proxy_pass   http://127.0.0.1:8082/;
}
  1. 情景3:proxy_pass后没有 / ,Nginx会把匹配部分带到代理的url
#访问地址:http://localhost:8081/model/asc.shtml
#最终代理:http://127.0.0.1:8082/model/asc.shtml
location /model/ {
  proxy_pass   http://127.0.0.1:8082;
}
  1. 情景4:proxy_pass后没有/但是有路径,Nginx会把把匹配内容追加到指定路径,并把路径作为前缀
#访问地址:http://localhost:8081/model/asc.shtml
#最终代理:http://127.0.0.1:8082/AAAmodel/asc.shtml
location /model/ {
  proxy_pass   http://127.0.0.1:8082/AAA;
}
  1. 情景5:proxy_pass存在/,那么就是绝对路径,location的匹配内容是针对用户的url请求的。
#访问地址:http://localhost:8081/model/asc.shtml
#最终代理:http://127.0.0.1:8082/asc.shtml
location /model {
  proxy_pass   http://127.0.0.1:8082/;
}
  1. 情景6:location的模糊匹配验证:location的路由末尾带/和不带/
#访问地址:http://localhost:8081/modelBBB/asc.shtml
#最终代理:http://127.0.0.1:8082/asc.shtml
location /model {
  proxy_pass   http://127.0.0.1:8082/;
}

4. 总结

4.1 知识要点

  1. location路由的精确匹配、前缀匹配、正则匹配、前缀匹配2、通用匹配
  2. location的末尾带/和不带/区别
  3. proxy_pass的末尾带/和不带/的区别

4.2 总结

  1. location是针对外部请求的一种匹配处理,包含精确、前缀、正则、通用匹配等。
  2. proxy_pass主要是针对location的处理,包含绝对路径和相对路径处理,区别就是末尾是否带/

5. 参考文档

  1. 参考文档:https://blog.csdn.net/m0_67391121/article/details/126113725
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值