locaiton有四種類型的匹配規(guī)則,分別為完全匹配(=)、前綴普通匹配(^~)、正則表達式匹配(~或者~*)、普通匹配
規(guī)則
說明
Location,用來快速進行資源定位,定義不同方式來處理或解決url請求,一般有:/ , = /, ~, ~* ,^~
優(yōu)先級是:(location = /)>(localtion^~)>(location ~| ~* )>(location /)
其中,~ 與 ~*,誰在上面先匹配誰.
# "/" 是直接到nginx發(fā)布目錄/usr/local/nginx/html/里來查資源,比如location.html location / { root html; index index.html index.htm; }
在發(fā)布目錄里創(chuàng)建location.html文件,內(nèi)容為:this is location.html。
執(zhí)行172.16.0.9/location.html時,服務器發(fā)布目錄里找這個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#
精準定位 一般用來匹配某個文件,優(yōu)先級高于 /
比如:
在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/目錄創(chuàng)建location.html。
可以看到,報404錯誤。這是因為,= / 優(yōu)先級高于/ ,服務器去第二個location里尋找location.html這個文件,而不是去第一個location里找。由于第二個location指定的目錄是/data,/data目錄下沒有l(wèi)ocation.html文件
在/data目錄下創(chuàng)建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下面。精準匹配優(yōu)先級是最高的,它不論是在配置文件內(nèi)容上面還是下面,服務器首先去找精準匹配的內(nèi)容
除以精準匹配,還有~ ,~* ,^~
~是對大小寫敏感,匹配時嚴格大小寫
~* 是對大小寫不敏感,匹配時不分大小寫。
^~用來匹配以uri開頭,匹配成功以后,會停止搜索后面的正則表達式匹配。
以上優(yōu)先最高的是精準匹配。location = /,其次是:^,然后是 和~* 這兩種看準在配置文件內(nèi)容上面,就先匹配誰,優(yōu)先級最低的是 /
以上規(guī)則在使用nginx時會被廣泛使用,比如多臺服務器做網(wǎng)站動靜分離時:
location ~ .*\.(html|htm|js|css|txt|png|jpg|jpeg|doc)$ { root html; }
到此這篇關于Nginx的location的常見規(guī)則優(yōu)先級的文章就介紹到這了,更多相關Nginx location規(guī)則優(yōu)先級內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!