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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM