Nginx Location匹配規則


前言:location是Nginx配置中的一個指令,用於訪問的URL匹配,而在這個location中所配置的每個指令將會啟動不同的 模塊去完成相應的工作。

理論部分

一、location語法:

location [=|~|~*|^~] uri { … }

其中,方括號中的四種標識符是可選項,用來改變請求字符串和uri的匹配方式。uri是待匹配的請求字符串,可以是不包含正則的字符串,這種模式被稱為“標准的uri";也可以包含正則,這種模式被稱為"正則uri"。例如:

location ~ .*\.(php|php5)?$ {
  root /var/www/html;
  ……
}

二、四種可選標識符:

標識符 描述
= 精確匹配:用於標准uri前,要求請求字符串和uri嚴格匹配。如果匹配成功就停止匹配,立即執行該location里面的請求。
~ 正則匹配:用於正則uri前,表示uri里面包含正則,並且區分大小寫
~* 正則匹配:用於正則uri前,表示uri里面包含正則,不區分大小寫
^~ 非正則匹配;用於標准uri前,nginx服務器匹配到前綴最多的uri后就結束,該模式匹配成功后,不會使用正則匹配。
普通匹配(最長字符匹配);與location順序無關,是按照匹配的長短來取匹配結果。若完全匹配,就停止匹配

操作案例部分

一、環境准備

為了方便驗證各匹配標識符,我們借助第三方模塊  echo模塊進行操作。安裝步驟向右看👉echo-nginx-module的安裝、配置、使用

二、匹配標識符案例

1. “=”精准匹配

location = /news/ {
            echo "test1";
        }
[root@www quail]# curl 192.168.249.132/news/
test1

2.  "~"區分大小寫正則匹配

location ~ \.(html) {
    echo 'test2';
}
location ~ \.(htmL) {
    echo 'test3';
}
[root@www quail]# curl 192.168.249.132/index.html
test2
[root@www quail]# curl 192.168.249.132/index.htmL
test3

3. “~*”不區分大小寫的正則匹配

location ~* \.(html){
            echo 'test4';
}
[root@www quail]# curl 192.168.249.132/index.htmL
test4
[root@www quail]# curl 192.168.249.132/index.html
test4

4. “^~”不進行正則匹配的標准匹配,只匹配前綴

location ^~ /index/ {
            echo 'test5';
}
[root@www quail]# curl 192.168.249.132/index/
test5
[root@www quail]# curl 192.168.249.132/index/heihei
test5
[root@www quail]# curl 192.168.249.132/index/asdnmkalsjd
test5

5.普通匹配

location / {
            echo 'test6';
}
[root@www quail]# curl 192.168.249.132
test6

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM