14人参与 • 2025-04-23 • Redis
nginx 1.19
在 nginx 的location
指令里,常用的匹配模式有:
=
)^~
),~
)~*)
location = /path { default_type text/html; return 200 'hello'; }
location ^~ /path { default_type text/html; return 200 'hello'; }
location /path { default_type text/html; return 200 'hello'; }
location ~ /path { default_type text/html; return 200 'hello'; }
location ~* /path { default_type text/html; return 200 'hello'; }
nginx会按照 精准模式 -> 前缀模式 -> 正则模式 的顺序来匹配。
精准模式优先级最高,匹配到后就不再继续匹配其它模式。而前缀模式匹配到后,还要视乎指令的配置情况,来决定要不要继续匹配正则模式。
看例子:
# 正则模式(大小写敏感) 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
都是正则模式(无论是否大小写敏感),从上之下,哪个先匹配到就哪个负责处理。
# 前缀模式(继续匹配正则) 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
来处理。
前缀模式(不继续匹配正则)也是同样的匹配规则。
# 前缀模式(不继续匹配正则) 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
处理。
看例子:
# 前缀模式(不继续匹配正则) location ^~ /a { default_type text/html; return 200 '333'; } # 前缀模式(继续匹配正则) location /a { default_type text/html; return 200 '444'; }
上面这段配置 nginx 会报错,因为在路径相同的情况下,这两种模式不能共存。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论