標籤:
nginx中location有幾種:
1.首碼,可以有=或^~修飾,比如
location / /開頭的
location /img/ /img/開頭的
location = /a.htm 剛好/a.htm
location ^~ /d 匹配後不再檢查Regexlocation。注意這個意思不是非Regex!除了~開頭其他都是非Regex,也就是首碼匹配
2.Regex,固定~或~*(不區分大小寫)開頭,比如:
location ~ \.html$
location ~* \.gif$
同時有多個location時,優先順序如下:
1.Test the URI against all prefix strings.
和所有首碼比較
2.The = (equals sign) modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops.
某個匹配首碼有=,則結束匹配
3.If the ^~ (caret-tilde) modifier prepends the longest matching prefix string, the regular expressions are not checked.
最長相符的有 ^~ 則結束匹配
4.Store the longest matching prefix string.
儲存最長相符
5.Test the URI against regular expressions.
再檢查 ~開頭的Regex
6.Break on the first matching regular expression and use the corresponding location.
第一個匹配的Regex,結束匹配
7.If no regular expression matches, use the location corresponding to the stored prefix string.
沒有正則匹配,則使用剛才最長首碼
所以,nginx的location中,~開頭的Regex配置順序會影響效果,而非~開頭的首碼匹配則和配置順序完全無關。
建議按如下順敘寫設定檔:
# =開頭的精確首碼匹配優先最高
location = /a.html{}
# ^~開頭的,禁止再匹配正則的首碼匹配
location ^~ /img{}
#但是這裡注意 ,如果後面有 location /img/abc{},且能匹配,那麼上面這條無法匹配
#所以建議一旦一個首碼以^~開頭,則其下的首碼配置也都用^~
# Regex,注意這部分需要考慮配置順序
location ~ \.*.htm$ {} #/a/b.htm匹配這個而不是下面的,僅僅因為這行在前
location ~ ^\/a {}
# 其他非 ^~ 與=開頭的首碼匹配,雖然順序無關,但建議把長的放前面
location /abc/df {}
#最後匹配的
location / {}
這樣檢查配置時,從上往下,匹配了,就不用看後面的了
nginx location優先順序詳解