当前位置首页 > Nginx知识

nginx的location配置(二)

阅读次数:278 次  来源:admin  发布时间:

ginx的location配置(二)

这一篇来记录location中的正则匹配

1、举例

1.1 配置举例1

1)在/www/server/nginx/html/下,新建文件image,该文件夹里面放置图片test.jpg

nginx的location配置(二)

2)打开/www/server/nginx/html/index.html,编辑

nginx的location配置(二)

ginx的配置里面添加:

1   location / {      #规则1
2        root html;
3        index index.html index.htm;
4   }
5 
6   location ~ image{ #规则2
7        root /var/www/image/;
8        index index.html;
9   }

如果我们访问http://test.php7.isee.wang/image/test.jpg,此时,“/”与“image/logo.png”也能匹配。那么,最终是哪个规则在发挥作用呢?别急,我们一步一步来看

首先直接访问:http://test.php7.isee.wang/

nginx的location配置(二)

由上图,我们看到,页面上面添加的图片并没有显示。

我们再直接访问下图片地址:http://test.php7.isee.wang/image/test.jpg

nginx的location配置(二)

这个时候就需要查看错误日志:

执行命令:tail -f /www/wwwlogs/test.php7.isee.wang.error.log

nginx的location配置(二)

分析:1) 从报错信息中,我们可以看到访问图片的地址通过nginx的location配置定位到规则2,但是没有找到相应的目录或者文件。

2) 但是这里有个问题是,这里定位到/var/www/image/image/test.jpg,我们配置的root是/var/www/image/,按理说这个地方应该是定位到/var/www/image/test.jpg。于是将root对应的配置改为/var/www/,再访问网址试试。

nginx的location配置(二)

由上图,可以看到图片正常显示出来啦

得出结果:普通匹配和正则匹配同时满足的情况下,正则表达式将会被最终使用,它会覆盖其它普通的匹配规则。

1.2 配置举例2

 1     location / {
 2          root html;
 3          index index.html index.htm;
 4     }
 5 
 6     location /foo {
 7          root  /var/www/html;
 8          index index.html index.htm;
 9     }
10 
11     location ~ image{
12          root /var/www/image/;
13          index index.html;
14     }

我们访问 http://test.php7.isee.wang/foo

nginx的location配置(二)

分析:对于uri “/foo”,两个location的patt,都能匹配他们。即 '/'能从左前缀匹配 '/foo' '/foo'也能左前缀匹配 '/foo',此时,真正访问 /var/www/html/index.html

原因:'/foo'匹配得更长

location定位流程图

nginx的location配置(二)

正则匹配

总结:location的命中过程是这样的

1) 先判断精准命中,如果命中,立即返回结果并结束解析过程。因此,可以看出使用精确匹配可以提高查找的速度。例如经常请求/的话,可以使用=来定义 location。

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

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

延伸分析:

a : 普通命中,顺序无所谓,是因为按照命中的长短来确定的。

: 正则命中,顺序有所谓,因为是从前往后命中的。

参考链接:https://www.jianshu.com/p/8c9e7fd54564

上一篇:Debian耳机声音问题
下一篇:debian国内源