Nginx location 匹配规则

语法规则:

  • = 开头表示精确匹配
  • ^~ 开头表示uri以某个常规字符串开头,理解为匹配url路径即可(非正则)
  • ~ 开头表示区分大小写的正则匹配
  • ~* 开头表示不区分大小写的正则匹配
  • !~!~*分别为区分大小写不匹配及不区分大小写不匹配的正则
  • / 通用匹配,任何请求都会匹配到

优先级:

= > ^~ > ~ | ~* > 最长前缀匹配 > /

  • 等号类型 = 的优先级最高。一旦匹配成功,则不再查找其他location的匹配项
  • ^~ 和通用匹配。使用前缀匹配,不支持正则表达式,如果有多个location匹配成功的话,不会终止匹配过程,会匹配表达式最长的那个
  • 如果上一步得到的最长的location为^~类型,则表示阻断正则表达式,不再匹配正则表达式
  • 如果上一步得到的最长的location不是^~类型,继续匹配正则表达式,只要有一个正则成功,则使用这个正则的location,立即返回结果,并结束解析过程

location匹配参数实例:

= 精确匹配

内容要同表达式完全一致才匹配成功

1
2
3
4
5
6
7
location = /abc/ {
.....
}

# 只匹配http://abc.com/abc
#http://example.com/abc [匹配成功]
#http://example.com/abc/index [匹配失败]

~ 执行正则匹配,区分大小写。

1
2
3
4
5
location ~ /Abc/ {
.....
}
#http://example.com/Abc/ [匹配成功]
#http://example.com/abc/ [匹配失败]

~* 执行正则匹配,忽略大小写

1
2
3
4
5
6
location ~* /Abc/ {
.....
}
# 则会忽略 uri 部分的大小写
#http://example.com/Abc/ [匹配成功]
#http://example.com/abc/ [匹配成功]

^~ 表示普通字符串匹配上以后不再进行正则匹配。

1
2
3
4
5
6
location ^~ /index/ {
.....
}
#以 /index/ 开头的请求,都会匹配上
#http://example.com/index/index.page [匹配成功]
#http://example.com/error/error.page [匹配失败]

不加任何规则时,默认是大小写敏感,前缀匹配,相当于加了 ~^~

1
2
3
4
5
6
7
location /index/ {
......
}
#http://example.com/index [匹配成功]
#http://example.com/index/index.page [匹配成功]
#http://example.com/test/index [匹配失败]
#http://example.com/Index [匹配失败]
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2018-2024 Outsrkem
  • 访问人数: | 浏览次数:

      请我喝杯咖啡吧~

      支付宝
      微信