一、环境
nginx 1.19
二、匹配模式
在 nginx 的location
指令里,常用的匹配模式有:
- 精准模式(
=
) - 前缀模式,不继续匹配正则(
^~
), - 前缀模式,继续匹配正则,
- 正则模式,大小写敏感(
~
) - 正则模式,大小写不敏感(
~*)
1. 精准模式
location = /path { default_type text/html; return 200 'hello'; }
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. 命中多个前缀模式时的优先级
# 前缀模式(继续匹配正则) 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 会报错,因为在路径相同的情况下,这两种模式不能共存。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论