目錄
- 一、Location / 匹配
- 二、Location = / 匹配
locaiton有四種類型的匹配規則,分別為完全匹配(=)、前綴普通匹配(^~)、正則表達式匹配(~或者~*)、普通匹配
規則
- 等號類型(=)的優先級最高。一旦匹配成功,則不再查找其他匹配項
- 前綴普通匹配(^~)優先級次之。不支持正則表達式。使用前綴匹配,如果有多個location匹配的話,則使用表達式最長的那個
- 正則表達式類型(~ ~*)的優先級次之。一旦匹配成功,則不再查找其他匹配項
- 常規字符串匹配,如果有多個location匹配的話,則使用表達式最長的那個
說明
- 先判斷精準命中,如果命中,立即返回結果并結束解析過程
- 若未結束,判斷前綴普通命中,如果有多個命中,使用表達式“最長”的命中結果,結束解析過程
- 若未結束,繼續判斷正則表達式的匹配,按正則表達式順序為準,由上至下一旦匹配成功1個,立即返回結果,并結束解析過程
- 若未結束,繼續普通命中,普通命中和前綴普通命中相似,順序無所謂,按照location表達式的長短來確定命中結果
Location,用來快速進行資源定位,定義不同方式來處理或解決url請求,一般有:/ , = /, ~, ~* ,^~
優先級是:(location = /)>(localtion^~)>(location ~| ~* )>(location /)
其中,~ 與 ~*,誰在上面先匹配誰.
一、Location / 匹配
# "/" 是直接到nginx發布目錄/usr/local/nginx/html/里來查資源,比如location.html
location / {
root html;
index index.html index.htm;
}
在發布目錄里創建location.html文件,內容為:this is location.html。
執行172.16.0.9/location.html時,服務器發布目錄里找這個location.html文件,并把結果this is loction.html返回出來,如下:
root@backupserver:/usr/local/nginx/html# ls
50x.html index.html
root@backupserver:/usr/local/nginx/html# echo "this is location.html" > ./location.html
root@backupserver:/usr/local/nginx/html# ls
50x.html index.html location.html
root@backupserver:/usr/local/nginx/html# /usr/local/nginx/sbin/nginx -s reload
root@backupserver:/usr/local/nginx/html# curl 172.16.0.9/location.html
this is location.html
root@backupserver:/usr/local/nginx/html#

二、Location = / 匹配
精準定位 一般用來匹配某個文件,優先級高于 /
比如:
在nginx配置文件中增加一個location = / ,定位到/data目錄。如下:
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
autoindex on;
root html;
index index.html index.htm;
}
location = /location.html {
root /data/;
index index.html;
}
重啟Nginx服務,測試:
1、先不在/data/目錄創建location.html。
可以看到,報404錯誤。這是因為,= / 優先級高于/ ,服務器去第二個location里尋找location.html這個文件,而不是去第一個location里找。由于第二個location指定的目錄是/data,/data目錄下沒有location.html文件

在/data目錄下創建location.html文件
root@backupserver:/usr/local/nginx/html# ls /data/
www
root@backupserver:/usr/local/nginx/html# echo "this is other location.com" > /data/location.html
root@backupserver:/usr/local/nginx/html# ls
50x.html index.html location.html
root@backupserver:/usr/local/nginx/html# curl 172.16.0.9/location.html
this is other location.com
root@backupserver:/usr/local/nginx/html#

上面可以看到,訪問 服務器是,服務器首先去location = /里面找,即使它在另一個location下面。精準匹配優先級是最高的,它不論是在配置文件內容上面還是下面,服務器首先去找精準匹配的內容
除以精準匹配,還有~ ,~* ,^~
~是對大小寫敏感,匹配時嚴格大小寫
~* 是對大小寫不敏感,匹配時不分大小寫。
^~用來匹配以uri開頭,匹配成功以后,會停止搜索后面的正則表達式匹配。
以上優先最高的是精準匹配。location = /,其次是:^,然后是 和~* 這兩種看準在配置文件內容上面,就先匹配誰,優先級最低的是 /
以上規則在使用nginx時會被廣泛使用,比如多臺服務器做網站動靜分離時:
location ~ .*\.(html|htm|js|css|txt|png|jpg|jpeg|doc)$ {
root html;
}
到此這篇關于Nginx的location的常見規則優先級的文章就介紹到這了,更多相關Nginx location規則優先級內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!