您的位置:首页 > 其它

location精准/正则匹配

2019-05-18 21:34 609 查看

location 语法

location 有”定位”的意思, 根据Uri来进行不同的定位.

在虚拟主机的配置中,是必不可少的,location可以把网站的不同部分,定位到不同的处理方式上.

比如, 碰到.php, 如何调用PHP解释器?  --这时就需要location

location 的语法

location [=|~|~*|^~] patt {

}

中括号可以不写任何参数,此时称为一般匹配

也可以写参数

因此,大类型可以分为3种

location = patt {} [精准匹配]

location patt{}  [一般匹配]

location ~ patt{} [正则匹配]

 


如何发挥作用?:

首先看有没有精准匹配,如果有,则停止匹配过程.

location = patt {

    config A

}


如果 $uri == patt,匹配成功,使用configA

    location = / {

       root   /var/www/html/;

       index  index.htm index.html;

    }

    (=/精准匹配到/,但是,这是个目录,index会去找文件,先找index.htm,没有就找index.html。如果index.html也没有,就走下一个location)

    location / {

      root   /usr/local/nginx/html;

      index  index.html index.htm;

    }

(先匹配精确匹配=/,不行再匹配/)

上面的配置分析:

如果访问  http://xxx.com/

定位流程是 

1: 精准匹配中 ”/”   ,得到index页为  index.htm

2: 再次访问 /index.htm , 此次内部转跳uri已经是”/index.htm” ,

根目录为/usr/local/nginx/html

3: 最终结果,访问了 /usr/local/nginx/html/index.htm

上面的例子如果改一下,改成准确到文件的精确访问:


若访问/,先去location =/,匹配/index.html,若有,就是/index.html,走location =/ index.html


再来看,正则也来参与.

location / {

    root   /usr/local/nginx/html;

    index  index.html index.htm;

}

 

location ~ image {

    root /var/www/image;

    index index.html;

}

 

如果我们访问  http://xx.com/image/logo.png

此时, “/” 与”/image/logo.png” 匹配

同时,”image”正则 与”image/logo.png”也能匹配,谁发挥作用?

正则表达式的成果将会使用.

 

图片真正会访问 /var/www/image/logo.png

 

 


location / {

    root   /usr/local/nginx/html;

    index  index.html index.htm;

}

 

location /foo {

    root /var/www/html;

    index index.html;

}

我们访问 http://xxx.com/foo

 对于uri “/foo”,   两个location的patt,都能匹配他们

即 ‘/’能从左前缀匹配 ‘/foo’, ‘/foo’也能左前缀匹配’/foo’,

此时, 真正访问 /var/www/html/index.html

原因:’/foo’匹配的更长,因此使用之.;





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

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置;

=:对URI做精确匹配;例如, http://www.magedu.com/, http://www.magedu.com/index.html

location  =  / {

...

}

~:对URI做正则表达式模式匹配,区分字符大小写;

~*:对URI做正则表达式模式匹配,不区分字符大小写;

^~:对URI的左半部分做匹配检查,不区分字符大小写;

不带符号:匹配起始于此uri的所有的url;

匹配优先级:=, ^~, ~/~*,不带符号;


= 严格匹配。如果这个查询匹配,那么将停止搜索并立即处理此请求。
~ 为区分大小写匹配(可用正则表达式)
!~为区分大小写不匹配
~* 为不区分大小写匹配(可用正则表达式)
!~*为不区分大小写不匹配
^~ 如果把这个前缀用于一个常规字符串,那么告诉nginx 如果路径匹配那么不测试正则表达式。


location ^~ /images/ {
 # 匹配任何以 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: