Nginx 設定 location匹配選擇機制
以下列配置為基準:
- 一般配置(最長路徑),會搜尋全部location後才挑選出符合最長路徑的配置檔
server {
...
server_name www.domain.com
...
# 最基本的配置,會匹配到所有 http://www.domain.com 的請求,但是優先順序會被排到正規表示法和最長路徑之後
# 例如 http://www.domain.com/abc 或 http://www.domain.com/xyz/test 兩者皆可符合該規則
location / {
....
}
# 匹配到以 /rotate 開頭的所有請求,但還不會馬上採用,會繼續往下搜尋是否有較長符合路徑的項目
location /rotate {
....
}
# 匹配到以 /rotate/taiwan 開頭的所有請求,也是不會馬上採用,但若是有來自 http://www.domain.com/rotate/taiwan/... 開頭的請求,則會取代上面 /rotate 配置成為優先保留項再繼續往下搜尋
location /rotate/taiwan {
....
}
# 匹配到以 /rotate/taiwan/keelung 開頭的所有請求,也是不會馬上採用,分為以下兩個情境
# 1. 來自 http://www.domain.com/rotate/taiwan/hsinchu 開頭的請求,依然會採用上面 /rotate/taiwan 的配置然後繼續往下搜尋
# 2. 來自 http://www.domain.com/rotate/taiwan/keelung 開頭的請求,則會取代上面 /rotate/taiwan 的配置成為新的優先保留項然後才再繼續往下搜尋
location /rotate/taiwan/keelung {
....
}
}
- 使用
=代表精準匹配,需要完全符合且匹配到會立即採用
server {
... other ...
server_name www.domain.com
... other ...
# 只能 http://www.domain.com 才能符合,後面不能帶任何字元,e.g. http://www.domain.com (O), http://www.domain.com/abc (X)
location = / {
....
}
# 來自 http://www.domain.com/news/taiwan/taipei 的要求會立即採用此配置
location = /news/taiwan/taipei {
....
}
}
- 若不區分大小寫使用
~*
- 第一個匹配到的規則會
立即採用
順序很重要
server {
... other ...
server_name www.domain.com
... other ...
# 1. 來自 http://www.domain.com/images 開頭的要求會匹配此規則且立即採用該配置,但 http://www.domain.com/Images 開頭的要求則不符合該規則
location ~ ^/images {
....
}
# 來自 http://www.domain.com/images 和 http://www.domain.com/Images 開頭的要求皆能符合此規則且會立即採用該配置
location ~* ^/images {
....
}
# 匹配所有以 .gif 和 .jpg 和 .jpeg 結尾的要求,這邊分兩個情境來說明
# 1. 來自 http://www.domain.com/Images/dog.jpg 的請求雖然符合該配置的規則,但是卻會先被上面的 ~* ^/images 這條規則先攔截,因此該請求其實是到不了這條規則的
# 2. 來自 http://www.domain.com/news/images/cat.gif 的請求符合該配置的規則且沒在其它地方被攔截,所以會立即採用該配置
location ~* \.(gif|jpg|jpeg)$ {
....
}
# 匹配所有 URI 路徑以 admin 和 swagger 和 api 開頭的要求,這邊分兩個情境來說明
# 例如來自 http://www.domain.com/admin/... 或 http://www.domain.com/Admin/... 開頭的請求皆符合此規則且會立即採用該配置
location ~* ^/(admin|swagger|api)/? {
....
}
}
- 使用
^~代表排除正規表達式的匹配,類似一般配置,不同的式一旦符合即馬上採用該配置
server {
...
server_name www.domain.com
# 匹配到所有請求,但還不會馬上採用,會繼續往下搜尋是否有其它較長符合路徑的項目
location / {
....
}
# 匹配到以 /news 開頭的所有請求,但還不會馬上採用,會繼續往下搜尋是否有較長符合路徑的項目
location /news {
....
}
# 匹配到以 /news/taiwan 開頭的所有請求,因為使用了 ^~ 所以如果有符合 /news/taiwan 開頭的 URI 會立即採用該配置,停止往下搜尋
# 1. 來自 http://www.domain.com/news/taiwan/taichung/index 的請求符合該配置的規則,所以採用該配置
# 2. 來自 http://www.domain.com/news/china/xingchang/index 的請求不符合該配置的規則,繼續往下搜尋
location ^~ /news/taiwan {
....
}
# 匹配到以 /news/china 開頭的所有請求,但還不會馬上採用,會繼續往下搜尋是否有較長符合路徑的項目
location /news/china {
....
}
}
| 參數 |
說明 |
是否立即採用 |
| X |
最長路徑 |
No |
| = |
精準匹配 |
Yes |
| ^~ |
效果似最長路徑(略過正規表達式),但會馬上採取 |
Yes |
| ~ |
正規表達式,區分大小寫 |
Yes |
| ~* |
正規表達式,不區分大小寫 |
Yes |