<!-- wp:quote -->
<p>location详解之精准匹配</p><!-- /wp:quote --> <!-- wp:more --> <!-- /wp:more --> <!-- wp:tadv/classic-paragraph --> <p>location是定位的意思,根据URL来进行不同的定位</p> <p>在虚拟主机的配置中,是必不可少的,location可以把网站的不同部分,定位到不同的处理方式上。</p> <p>比如,碰到PHP,如何调用PHP的解释器?这时就需要location</p> <h2>location的语法</h2>
location [=|~|~*|^~] patt {
}
<p>这个语法分为三种,第一个时location,然后是修饰符,然后时patt,修饰符可以不写。</p>
<p>如何发挥作用?</p>
<p>首先看有没有精准匹配,如果有,则停止匹配过程,</p>
location = patt{
config A
}
<p>如果$ url == patt ,匹配成功,使用config A</p>
<p>我们来做个实验,创建两个文件夹,并且随便写两个HTML文件:</p>
mkdir /var/www/html/
cd /var/www/html/
vim index.htm
vim index.html
<p>这个htm和HTML里面的文件内容要不一样,这里就不编辑了</p>
<p>然后在nginx的配置文件里添加一段这样的话:</p>
location = / {
root /var/www/html;
index index.html index.htm;
}
<!-- /wp:tadv/classic-paragraph -->
<!-- wp:paragraph -->
<p>可以看下我的添加位置</p>
<!-- /wp:paragraph -->
<!-- wp:tadv/classic-paragraph -->
<p>注意一下,我的位置是把添加的那一段放在上面的。然后需要注意的是,我添加的那段话是说,我们要精准匹配“/var/www/html/”下面的index.htm,和index.html现在我们一切就绪,重启nginx</p>
[root@localhost nginx]# ./sbin/nginx -s reload
<!-- /wp:tadv/classic-paragraph -->
<!-- wp:paragraph -->
<p>看看效果,按理来说应该是访问的精准匹配出来的那个结果,也就是/var/www/html/index.html才对,但是当我们打开网站之后发现却是下面这样的:</p>
<!-- /wp:paragraph -->
<!-- wp:tadv/classic-paragraph -->
<p>
[root@localhost nginx]# more /var/www/html/index.html
<html>
This is =
</html>
<!-- /wp:tadv/classic-paragraph -->
<!-- wp:paragraph -->
<p>上面这个才是我的内容。可却打开了nginx的默认页面,那么我们试试把配置文件中的精准匹配的index.html和index.htm位置进行掉换一下看看,也就是写成下面这样:</p>
<!-- /wp:paragraph -->
<!-- wp:tadv/classic-paragraph -->
location = / {
root /var/www/html;
index index.htm index.html;
}
location / {
root html;
index index.html index.htm;
}
<p>然后重启nginx别忘了</p>
./sbin/nginx -s reload
<!-- /wp:tadv/classic-paragraph -->
<!-- wp:paragraph -->
<p>之后我们却看到了下面的404页面:</p>
<!-- /wp:paragraph -->
<!-- wp:tadv/classic-paragraph -->
<p>
[root@localhost nginx]# ls /var/www/html/ index.htm index.html
<p>却读取不到,原因很简单,我们这里访问的IP地址只是访问了一个“/”</p>
<p>如果访问一个http://wdwad.com/</p>
<p> 定位流程如下</p>- 精准匹配中“/”,得到index页面为index.htm
- 再次访问/index.htm,此次内部跳转URL已经是“/index.htm”,根目录成了/usr/local/nginx/html
- 所以最终访问了/usr/local/nginx/html/index.htm,但是这里却没有index.htm所以最终成了404
<p>我们可以再做一个实验,将nginx的配置改成下面的样子:</p>
location = /index.htm { root /var/www/html; index index.htm index.html; } location / { root html; index index.html index.htm; }
<p>注意这次我说明了访问哪里:</p>
<p>

