【轉】nginx location匹配規則

來源:互聯網
上載者:User

標籤:

轉載請保留:http://www.nginx.cn/115.html

location匹配命令

~      #波浪線表示執行一個正則匹配,區分大小寫
~*    #表示執行一個正則匹配,不區分大小寫
^~    #^~表示一般字元匹配,如果該選項匹配,只匹配該選項,不匹配別的選項,一般用來匹配目錄
=      #進行一般字元精確匹配
@     #"@" 定義一個命名的 location,使用在內部定向時,例如 error_page, try_files

 

location 匹配的優先順序(與location在設定檔中的順序無關)
= 精確匹配會第一個被處理。如果發現精確匹配,nginx停止搜尋其他匹配。
一般字元匹配,Regex規則和長的塊規則將被優先和查詢匹配,也就是說如果該項匹配還需去看有沒有Regex匹配和更長的匹配。
^~ 則只匹配該規則,nginx停止搜尋其他匹配,否則nginx會繼續處理其他location指令。
最後匹配理帶有"~"和"~*"的指令,如果找到相應的匹配,則nginx停止搜尋其他匹配;當沒有Regex或者沒有Regex被匹配的情況下,那麼匹配程度最高的逐字匹配指令會被使用。

location 優先順序官方文檔

  1. Directives with the = prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops.
  3. Regular expressions, in order of definition in the configuration file.
  4. If #3 yielded a match, that result is used. Else the match from #2 is used.
  1. =首碼的指令嚴格匹配這個查詢。如果找到,停止搜尋。
  2. 所有剩下的常規字串,最長的匹配。如果這個匹配使用^?首碼,搜尋停止。
  3. Regex,在設定檔中定義的順序。
  4. 如果第3條規則產生匹配的話,結果被使用。否則,如同從第2條規則被使用。

 

例如

 
123456789101112131415161718 location  = / {  # 只匹配"/".  [ configuration A ]}location  / {  # 匹配任何請求,因為所有請求都是以"/"開始  # 但是更長字元匹配或者Regex匹配會優先匹配  [ configuration B ]}location ^~ /images/ {  # 匹配任何以 /images/ 開始的請求,並停止匹配 其它location  [ configuration C ]}location ~* .(gif|jpg|jpeg)$ {  # 匹配以 gif, jpg, or jpeg結尾的請求.  # 但是所有 /images/ 目錄的請求將由 [Configuration C]處理.     [ configuration D ]}

請求URI例子:

  • / -> 符合configuration A
  • /documents/document.html -> 符合configuration B
  • /images/1.gif -> 符合configuration C
  • /documents/1.jpg ->符合 configuration D

@location 例子
error_page 404 = @fetch;

location @fetch(
proxy_pass http://fetch;
)

 

【轉】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.