nginx location優先順序詳解

來源:互聯網
上載者:User

標籤:

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優先順序詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.