Nginx实践:(2) Nginx语法之localtion

1. 概念

location是根据uri进行不同的定位。在虚拟主机的配置中,是必不可少的。location可以将网站的不同部分,定位到不同的处理方式上。

location语法格式如下:

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

}

其中:

(1) 当[]中的内容均不填写时,表示一般匹配

(2) "="表示精准匹配

(3) "~"表示正则匹配 

2. 精确匹配

当uri匹配时,首先检测是否存在精准匹配,如果存在,则停止匹配过程。

例1:

// 如果$uri==patt,则匹配成功,使用config A
location = patt {
    config A
}

 例2:

location = / {
    root /var/www/html/;
    index index.htm index.html;  
}

location / {
    root /usr/local/nginx/html;
    index index.html index.htm;
}

 如果访问http://ip:port/,则其定位流程是:a) 精准匹配" = /",得到index页为index.htm; b) 再次访问/index.htm,此次内部跳转已经是"/index.htm"(一般匹配),其根目录为/usr/local/nginx/html; c) 最终结果,访问了/usr/local/nginx/html/index.htm

3. 正则匹配 

location / {
    root   /usr/local/nginx/html;
    index  index.html index.htm;
}

location ~ image {
    root /var/www/;
    index index.html;
}

 假设服务器存在/usr/local/nginx/html/image/1.jpg路径,当我们访问http://xx.com/image/1.jpg时,此时"/"与"/image/1,jpg"匹配,同时 "image"正则与"image/1.jpg"也能够匹配,二者谁会发挥作用?答案是二者均会起作用,但是最终起作用的是正则表达式,正则表达式会将之前匹配的覆盖掉,因此图片真正访问/var/www/image/1.jpg。

 4. 一般匹配

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'匹配的更长,优先进行匹配。

5. location命中匹配过程

(1) 首先判断精准命中,如果命中,立即返回结果并结束解析过程

(2) 判断普通命中,如果有多个命中,"记录"下来"最长"的命中结果(注意:记录但不结束,最长的为准)

(3) 继续判断正则表达式的解析结果,按配置中的正则表达式顺序为准,由上到下开始匹配,一旦匹配成功一个,立即返回结果,并结束解析过程

延伸分析:a: 普通命中顺序无所谓,是因为按命中的长短来确定的 b: 正则命中,顺序有所谓,是因为从前往后命中的

原文地址:https://www.cnblogs.com/mengrennwpu/p/9614263.html