本文主要是介绍Nginx location匹配模式与规则详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《Nginxlocation匹配模式与规则详解》:本文主要介绍Nginxlocation匹配模式与规则,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教...
一、环境
Nginx 1.19
二、匹配模式
在 Nginx 的location指令里,常用的匹配模式有:
- 精准模式(
=) - 前缀模式,不继续匹配正则(
^~), - 前缀模式,继续匹配正则,
- 正则模式,大小写敏感(
~) - 正则模式,大小写不敏感(
~*)
1. 精准模式
2. 前缀模式(不继续匹配正则)
location ^~ /path {
default_type text/html;
return 200 'hello';
}3. 前缀模式(继续匹配正则)
location /path {
default_type text/html;
return 200 'hello';
}4. 正则模式(大小写敏感)
location ~ /path {
default_type text/html;
return 200 'hello';
}5. 正则模式(大小写不敏感)
location ~* /path {
default_type text/html;
return 200 'hello';
}Nginx会按照 精准模式 -> 前缀模式 -> 正则模式 的顺序来匹配。
精准模式优先级最高,匹配到后就不再继续匹配其它模式。而前缀模式匹配到后,还要视乎指令的配置情况,来决定要不要继续匹配正则模式。
三、需要注意的地方
1. 命中多个正则模式时的优先级
看例子:
# 正则模式(大小写敏感)
location ~ /a {
default_type text/html;
return 200 '111';
}
# 正则模式(大小写敏感)
location ~ /a/b {
default_type text/html;
return 200 '222';
}如果访问http://localhost/a/b,会命中哪个location?答案是第一个。
因为两个location都是正则模式(无论是否大小写敏感),从上之下,哪个先匹配到就哪个负责处理。
2. 命中多个前缀模javascript式时的优先级
# 前缀模式(继续匹配正则)
location /a {
default_type text/html;
return 200 '111';
}
# 前缀模式(继续匹配正则)
location /a编程/b {
default_type text/html;
return 200 '222';
}- 访问
http://localhost/a,命中第一个; - 访问
http://localhost/a/b,命中第二个; - 访问
http://localhost/a/b/c,命中第二个;
简单来说,哪个location匹配到的字符串最长,就由哪个来处理,比如http://localhost/a/b/c能匹配到的最长字符串是/a/b,所以由第二个location来处理。
前缀模式(不继续匹配正则)也是同样的匹配规则。
3. 命中多个不同模式时的优先级
# 前缀模式(不继续匹配正则)
location ^~ /a {
default_type text/html;
return 200 '111';
}
# 前缀模式(继续匹配正则)
location /a/b {
default_type text/html;
return 200 '333';
}
# 正则模式(大小写敏感)
location ~ /a/b {
default_type text/html;
return 200 '222';
}访问http://localhost/a/b,会命中第三个location。
前面两个location都是前缀模式,由匹配字符串最长的处理(即第二个)。第二个location没编程有阻止继续匹配正则,于是又继续匹配第三个location(正则模式),所以最后是由第三个location处理。
4. 两种前缀模式不能同时存在
看例子:
# 前缀模式(不继续匹配正则)
location ^~ /a {
default_type text/html;
return 200 '333';
}
# 前缀模式(继续匹配正则)
location /a {
default_type text/html;
return 200 '444';
}上面这段配置 Nginx 会报错,因为在路径相同的情况下,这两种模式不能共存。
总结
这篇关于Nginx location匹配模式与规则详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!