原来一直以为location的优先级是先后顺序,结果有次项目中傻眼了,赶紧百度一下,下面的内容参考了这个链接

location表达式类型

~ 表示执行一个正则匹配,区分大小写
~* 表示执行一个正则匹配,不区分大小写
^~ 表示普通字符匹配。使用前缀匹配。如果匹配成功,则不再匹配其他location。
= 进行普通字符精确匹配。也就是完全匹配。
@ "@" 定义一个命名的 location,使用在内部定向时,例如 error_page, try_files

location优先级说明

在nginx的location和配置中location的顺序没有太大关系。正location表达式的类型有关。相同类型的表达式,字符串长的会优先匹配。
以下是按优先级排列说明:
第一优先级:等号类型(=)的优先级最高。一旦匹配成功,则不再查找其他匹配项。
第二优先级:^~类型表达式。一旦匹配成功,则不再查找其他匹配项。
第三优先级:正则表达式类型(~ ~*)的优先级次之。如果有多个location的正则能匹配的话,则使用正则表达式最长的那个。
第四优先级:常规字符串匹配类型。按前缀匹配。

下面是我的一段示例代码,配置如下

user  root;
http {
include mime.types;
default_type application/octet-stream; sendfile on;
keepalive_timeout ;
server {
listen ;
location ^~ /hls {
content_by_lua 'ngx.say("success /hls")
ngx.exit(ngx.OK)';
}
location / {
content_by_lua 'ngx.say("success")
ngx.exit(ngx.OK)';
}
location ~* \.(m3u8|ts)$
{
content_by_lua 'ngx.say("success *.m3u8")
ngx.exit(ngx.OK)';
}
}
}

那么如下请求如下链接,会输出什么呢

curl http://127.0.0.1:38080/demo/test.jpg
curl http://127.0.0.1:38080/demo/test.m3u8
curl http://127.0.0.1:38080/hls/test.m3u8
curl http://127.0.0.1:38080/hls/test.jpg

下面是输出结果哈

success
success *.m3u8
success /hls
success /hls
05-28 17:36