文章目录
1. Nginx配置规则
location=/uri
=号开头表示精确匹配,只有完全匹配才能生效。
location ^~/uri
^~开头对URL路径进行前缀匹配,并且在正则之前
location ~pattern
~开头表示区分大小写的正则匹配
location /uri
不带任何修饰符,也表示前缀匹配,但是在正则匹配之后,如果没有正则命中,命中最长的规则
location /
通用匹配,任何未匹配到其他location的请求都会被匹配到,相当于switch中的default
1.1 优先级总结
- 精确匹配
>
带有修饰符的前缀匹配>
正则匹配>
不带任何修饰符的前缀匹配>
通用匹配
2. location是否以/
结尾
- 在nginx中location进行的是模糊匹配
1、没有“/”结尾时,location /abc/def可以匹配/abc/defghi请求,也可以匹配/abc/def/ghi等
2、而有“/”结尾时,location /abc/def/不能匹配/abc/defghi请求,只能匹配/abc/def/anything这样的请求
- 总结:
“/” 就像一个标识符,location的模糊匹配只能匹配标识符后面的内容
3. proxy_pass配置规则
- 配置proxy_pass时,当在后面的url加上
/
,相当于是绝对路径,则Nginx不会把location中匹配的路径部分加入到代理uri。 - 如果配置proxy_pass时,后面没有
/
,Nginx则会把匹配的路径部分加入代理URI
3.1 location的六种情况
- 情景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/;
}
- 情景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/;
}
- 情景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;
}
- 情景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;
}
- 情景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/;
}
- 情景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 知识要点
- location路由的精确匹配、前缀匹配、正则匹配、前缀匹配2、通用匹配
- location的末尾带
/
和不带/
区别 - proxy_pass的末尾带
/
和不带/
的区别
4.2 总结
location
是针对外部请求的一种匹配处理,包含精确、前缀、正则、通用匹配等。proxy_pass
主要是针对location的处理,包含绝对路径和相对路径处理,区别就是末尾是否带/