Nginx配置中Location的匹配规则
Location匹配的语法规则:
location [=|~|~*|^~] /uri/ { … }
= 表示精确匹配
^~ 表示以某个常规字符串开头的url即可;
~ 表示区分大小写的正则匹配
~* 表示不区分大小写的正则匹配
!~(!~*)表示区分大小写不正则匹配和不区分大小写不正则匹配
@ 用于处理内部重定向
匹配顺序:
1)匹配顺序:先匹配普通location,再匹配正则location【跟配置顺序无关】
2)“普通 location ”的匹配规则包含“最大前缀匹配”和“严格匹配”,其中“严格匹配”包含了普通location严格匹配和带=前缀的严格匹配;“普通location”最终会找到“最大前缀匹配”或者“严格匹配”的location,如果找到“严格匹配”则不再继续匹配其他规则;【跟配置顺序无关】
例如:http://www.xxxyyy.com:8080/
会严格匹配上[ configuration A ]
location = / {
# matches the query / only.
[ configuration A ]
}
location ~ / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
[ configuration B ]
}
3)“正则location”匹配规则找到第一个匹配的location,就不在继续匹配后面的location;【跟配置顺序有关】
4)匹配完“普通 location ”后,有的时候需要继续匹配“正则 location ”,有的时候则不需要继续匹配“正则 location ”。
两种情况下,不需要继续匹配正则 location :
(1) 当普通 location 前面指定了“ ^~ ”,特别告诉 Nginx 本条普通 location 一旦匹配上,则不需要继续正则匹配;
(2) 当普通location 恰好严格匹配上,不是最大前缀匹配,则不再继续匹配正则。
严格匹配:一,普通location,无任何前缀符号的;二,带=号前缀符号的严格匹配。
5)最终生效的location配置:
普通location是“严格匹配”或者带有“ ^~ ”前缀,则直接使用普通location;如果既有普通location的最大前缀匹配,也有正则匹配,则正则匹配覆盖最大前缀匹配。
例如:
location = / {
# matches the query / only.
[ configuration A ]
}
location / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
[ configuration B ]
}
location /documents/ {
# matches any query beginning with /documents/ and continues searching,
# so regular expressions will be checked. This will be matched only if
# regular expressions don't find a match.
[ configuration C ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
# Configuration D.
[ configuration E ]
}
请求示例,匹配的Location:
- / -> configuration A
- /index.html -> configuration B
- /documents/document.html -> configuration C
- /images/1.gif -> configuration D
- /documents/1.jpg -> configuration E