nginx location規則以及優先順序詳解
阿新 • • 發佈:2022-04-19
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