目錄
- 一、語法
- 二、匹配順序
- 三、root 與 alias 的區別
- 四、server 和 location 中的 root
- 總結
一、語法
Location 是 Nginx 中一個非常核心的配置,關于Location,舉個簡單的配置例子:
server {
listen 80;
server_name 10.0.7.115;
location / {
root /data/app/;
index index.html;
}
}
當訪問 http://10.0.7.115:80 的時候,返回的是 /data/app/index.html 文件。
Location具體語法:
location [ = | ~ | ~* | ^~ ] uri { … }
重點看方括號中的 [ = | ~ | ~* | ^~ ],其中 | 分隔的內容表示你可能會用到的語法,其中:
= 表示精確匹配:
location = /test {
return 200 "hello";
}
例如:
/test ok /test/ not ok /test2 not ok /test/2 not ok
~ 表示區分大小寫的正則匹配:
location ~ ^/test$ {
[configuration]
}
例如:
/test ok /Test not ok /test/ not ok /test2 not ok
~* 表示不區分大小寫的正則匹配:
location ~* ^/test$ {
[configuration]
}
例如:
/test ok /Test ok /test/ not ok /test2 not ok
^~ 表示 uri 以某個字符串開頭:
location ^~ /images/ {
[configuration]
}
例如:
/images/1.gif ok
/ 表示通用匹配:
location / {
[configuration]
}
例如:
/index.html ok
location /test {
[configuration]
}
例如:
/test ok /test2 ok /test/ ok
二、匹配順序
Location的定義分為兩種:
- 前綴字符串(prefix string)
- 正則表達式(regular expression),具體為
前面帶 ~* 和 ~ 修飾符的
當存在多個 Location 的時候,匹配的順序為:
檢查使用前綴字符串的 locations,在使用前綴字符串的 locations 中選擇最長匹配的,并將結果進行儲存;
- 如果符合帶有
=修飾符的URI,則立刻停止匹配; - 如果符合帶有
^~修飾符的URI,則也立刻停止匹配; - 然后按照定義文件的順序,檢查正則表達式,匹配到就停止;
- 當正則表達式匹配不到的時候,使用之前儲存的前綴字符串;
總結:
在順序上:
- 前綴字符串順序不重要,按照匹配長度來確定;
- 正則表達式則按照定義順序;
在 優先級上:
=修飾符最高,^~次之,再者是正則,最后是前綴字符串匹配。
我們舉幾個簡單的例子進行說明
請求URI如下:
/document
示例一:
配置:
server {
location /doc {
[ configuration A ]
}
location /docu {
[ configuration B ]
}
}
匹配結果:
configuration B
注:雖然 /doc 也能匹配到,但 在順序上,前綴字符串順序不重要,按照匹配長度來確定。
示例二:
server {
location ~ ^/doc {
[ configuration A ]
}
location ~ ^/docu {
[ configuration B ]
}
}
匹配結果:
configuration A
注:雖然 ~ ^/docu 也能匹配到,但 正則表達式則按照定義順序。
示例三:
server {
location ^~ /doc {
[ configuration A ]
}
location ~ ^/docu {
[ configuration B ]
}
}
匹配結果:
configuration A
注:雖然 ~ ^/docu 也能匹配到,但 ^~ 的 優先級更高。
示例四:
server {
location /document {
[ configuration A ]
}
location ~ ^/docu {
[ configuration B ]
}
}
匹配結果:
configuration B
注:雖然 /document 也能匹配到,但 正則的優先級更高。
三、root 與 alias 的區別
當我們這樣設置 root 的時候:
location /i/ {
root /data/w3;
}
當請求 /i/top.gif,/data/w3/i/top.gif 會被返回。
當我們這樣設置 alias 的時候:
location /i/ {
alias /data/w3/images/;
}
當請求 /i/top.gif,/data/w3/images/top.gif 會被返回。
兩者的區別:
root是直接拼接root + location;alias是用alias替換location;
四、server 和 location 中的 root
server 和 location 中都可以使用 root,舉個例子:
server {
listen 80;
server_name 10.0.7.115;
root /data/app/;
location / {
root /data/web/;
index index.html;
}
}
如果兩者都出現,是怎樣的優先級呢?
簡單的來說,就是 就近原則,如果 location 中能匹配到,就是用 location 中的 root 配置,忽略 server 中的 root,當 location 中匹配不到的時候,則使用 server 中的 root 配置。






