nginx location規則以及優先級詳解


nginx 配置文件里往往有多個location來區分不同的路徑來執行不同的配置
 
在nginx配置文件中,location主要有這幾種形式:
1、~   # 使用波浪符“ ~”區分大小寫正則匹配,如 location ~ /abc { }
2、~*  #不區分大小寫的正則匹配,如 location ~* /abc { }
3、^~  # 匹配路徑的前綴,如果找到停止搜索,如 location ^~ /abc { }
4、=   #精確匹配 如 location = /abc { }
5、    #普通路徑前綴匹配 如 location /abc { }

匹配優先級原則越精准越優先

優先級
4 > 3 > 2 > 1 > 5
 
解釋一下各個格式:
location = / {
# 精確匹配 / ,主機名后面不能帶任何字符串
[ configuration A ]
}

location / {
# 因為所有的地址都以 / 開頭,所以這條規則將匹配到所有請求
# 但是正則和最長字符串會優先匹配
[ configuration B ]
}
location /documents/ {

# 匹配任何以 /documents/ 開頭的地址,匹配符合以后,還要繼續往下搜索
# 只有后面的正則表達式沒有匹配到時,這一條才會采用這一條
[ configuration C ]
}

location ~ /documents/Abc {

# 匹配任何以 /documents/ 開頭的地址,匹配符合以后,還要繼續往下搜索
# 只有后面的正則表達式沒有匹配到時,這一條才會采用這一條
[ configuration CC ]
}
location ^~ /images/ {

# 匹配任何以 /images/ 開頭的地址,匹配符合以后,停止往下搜索正則,采用這一條。
[ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {

# 匹配所有以 gif,jpg或jpeg 結尾的請求(不區分大小寫)
# 然而,所有請求 /images/ 下的圖片會被 config D 處理,因為 ^~ 到達不了這一條正則
[ configuration E ]
}

location /images/ {

# 字符匹配到 /images/,繼續往下,會發現 ^~ 存在
[ configuration F ]
}

location /images/abc {

# 最長字符匹配到 /images/abc,繼續往下,會發現 ^~ 存在
# F與G的放置順序是沒有關系的
[ configuration G ]
}

location ~ /images/abc/ {

# 只有去掉 config D 才有效:先最長匹配 config G 開頭的地址,繼續往下搜索,匹配到這一條正則,采用
[ configuration H ]
}

 

 
再來分析一下A-H配置的執行順序。
下面2個配置同時存在時
location = / {
[ configuration A ]
}

location / {
[ configuration B ]
}
此時A生效,因為=/優先級高於/
 
下面3個配置同時存在時:
location  /documents/ {
[ configuration C ]
}

location ~ /documents/ {

[configuration CB]

}

location ~ /documents/abc {
[ configuration CC ]
}
 
 
當訪問的url為/documents/abc/1.html,此時CC生效,首先CB優先級高於C,而CC更優先於CB
 
下面4個配置同時存在時
location ^~ /images/ {
[ configuration D ]
}

location /images/ {
[ configuration F ]
}

location /images/abc {
[ configuration G ]
}

location ~ /images/abc/ {
[ configuration H ]
}
 
當訪問的鏈接為/images/abc/123.jpg時,此時D生效。雖然4個規則都能匹配到,但^~優先級是最高的。
 
若^~不存在時,H優先,因為~/images/ > /images/
 
而/images/和/images/abc同時存在時,/images/abc優先級更高,因為后者更加精准
 
下面兩個配置同時存在時
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}

location ~ /images/abc/ {

[ configuration H ]
}

 

 
當訪問的鏈接為/images/abc/123.jpg時,E生效。因為上面的規則更加精准。
 
 
參考:
1、https://cloud.tencent.com/developer/article/1119218
2、http://haiyang.me/read.php?key=361

 


免責聲明!

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



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