原来一直觉得location的优先级是前后顺序,结果有次项目中傻眼了,赶忙百度一下,下面的内容参考了这个连接nginx
~ 表示执行一个正则匹配,区分大小写
~* 表示执行一个正则匹配,不区分大小写
^~ 表示普通字符匹配。使用前缀匹配。若是匹配成功,则再也不匹配其余location。
= 进行普通字符精确匹配。也就是彻底匹配。
@ "@" 定义一个命名的 location,使用在内部定向时,例如 error_page, try_files正则表达式
在nginx的location和配置中location的顺序没有太大关系。正location表达式的类型有关。相同类型的表达式,字符串长的会优先匹配。
如下是按优先级排列说明:
第一优先级:等号类型(=)的优先级最高。一旦匹配成功,则再也不查找其余匹配项。
第二优先级:^~类型表达式。一旦匹配成功,则再也不查找其余匹配项。
第三优先级:正则表达式类型(~ ~*)的优先级次之。若是有多个location的正则能匹配的话,则使用正则表达式最长的那个。
第四优先级:常规字符串匹配类型。按前缀匹配。app
下面是个人一段示例代码,配置以下curl
user root; http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 38080; 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)'; } } }
那么以下请求以下连接,会输出什么呢lua
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
结url
果spa
在code
下server
面blog
。
。
。
下面是输出结果哈
success success *.m3u8 success /hls success /hls