nginx配置location總結

location匹配順序

  1. "="前綴指令匹配,若是匹配成功,則中止其餘匹配
  2. 普通字符串指令匹配,順序是從長到短,匹配成功的location若是使用^~,則中止其餘匹配(正則匹配)
  3. 正則表達式指令匹配,按照配置文件裏的順序,成功就中止其餘匹配
  4. 若是第三步中有匹配成功,則使用該結果,不然使用第二步結果

注意點

  1. 匹配的順序是先匹配普通字符串,而後再匹配正則表達式。另外普通字符串匹配順序是根據配置中字符長度從長到短,也就是說使用普通字符串配置的location順序是可有可無的,反正最後nginx會根據配置的長短來進行匹配,可是須要注意的是正則表達式按照配置文件裏的順序測試。找到第一個比配的正則表達式將中止搜索。html

  2. 通常狀況下,匹配成功了普通字符串location後還會進行正則表達式location匹配。有兩種方法改變這種行爲,其一就是使用「=」前綴,這時執行的是嚴格匹配,而且匹配成功後當即中止其餘匹配,同時處理這個請求;另一種就是使用「^~」前綴,若是把這個前綴用於一個常規字符串那麼告訴nginx 若是路徑匹配那麼不測試正則表達式。nginx

匹配模式及順序

  location = /uri    =開頭表示精確匹配,只有徹底匹配上才能生效正則表達式

  location ^~ /uri   ^~ 開頭對URL路徑進行前綴匹配,而且在正則以前。瀏覽器

  location ~ pattern  ~開頭表示區分大小寫的正則匹配。
測試

  location ~* pattern  ~*開頭表示不區分大小寫的正則匹配。spa

  location /uri     不帶任何修飾符,也表示前綴匹配,可是在正則匹配以後code

  location /      通用匹配,任何未匹配到其它location的請求都會匹配到,至關於switch中的default htm

 

實驗案例

  • 測試"^~"和"~",nginx配置以下。瀏覽器輸入http://localhost/helloworld/test,返回601。如將#1註釋,#2打開,瀏覽器輸入http://localhost/helloworld/test,返回603。注:#1和#2不能同時打開,如同時打開,啓動nginx會報nginx: [emerg] duplicate location "/helloworld"...,由於這兩個都是普通字符串。
location ^~ /helloworld {      #1
    return 601;
}
        
#location /helloworld {        #2
#    return 602;
#}

location ~ /helloworld {
    return 603;
}    
  • 測試普通字符串的長短(普通字符串的匹配與順序無關,與長短有關)。瀏覽器輸入http://localhost/helloworld/test/a.html,返回601。瀏覽器輸入http://localhost/helloworld/a.html,返回602。
location /helloworld/test/ {        #1
    return 601;
}
        
location /helloworld/ {                #2
    return 602;
}
  • 測試正則表達式的順序(正則匹配與順序相關)。瀏覽器輸入http://localhost/helloworld/test/a.html,返回602;將#2和#3調換順序,瀏覽器輸入http://localhost/helloworld/test/a.html,返回603
location /helloworld/test/ {        #1
    return 601;
}

location ~ /helloworld {            #2
    return 602;
}
        
location ~ /helloworld/test {        #3
    return 603;
}
相關文章
相關標籤/搜索