Nginx Location匹配規則

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

理論部分

1、location語法:

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

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

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

2、四種可選標識符:

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

操做案例部分

1、環境準備

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

2、匹配標識符案例

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
相關文章
相關標籤/搜索