location 介绍

location 有”定位”的意思, 根据Uri来进行不同的定位. 在虚拟主机的配置中,是必不可少的,location可以把网站的不同部分,定位到不同的处理方式上.

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

location 的语法

location [=|~|~*|^~] patt {
}
- 中括号可以不写任何参数,此时称为一般匹配
- 也可以写参数

根据参数的特性,可以大致分为以下三种:

location = patt {} [精准匹配]
location   patt {} [一般匹配]
location ~ patt {} [正则匹配]

location匹配规格介绍

  • 若匹配到目录,nginx 会内部转发一次。
  • 若匹配到文件,有则显示,无则报错。

三种匹配方式介绍

一般匹配

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

注意:/ 后可以跟参数,记录最长的匹配结果。

等值匹配

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

注意:/ 后可以跟参数,匹配成功后直接返回精确结果。

正则匹配

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

注意:/ 后可以跟参数,优先级略低于等值匹配,任一正则命中,返回正则命中结果,并停止匹配。注意:正则匹配会在root目录后加上image, 即如果访问:http://localhost/image/mm.jpg, 则访问的是/var/www/html/image/mm.jpg

三个匹配优先级介绍

  • 1)先判断精准命中,如果命中,立即返回结果并返回结果解析过程。
  • 2)判断普通命中后,如果有多个命中,“记录”下来“最长”的命中结果(注意:记录但不结束,最长的为准)
  1. 判断正则匹配结果,一旦有一个命中,返回匹配结果并结束解析过程。

常见易错多location配置

等值与一般匹配同时使用

代码如下:

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

location / {
    root   html;
    index  index.html index.htm;
}

上述配置后访问:http://localhost/,注意其它location配置先不要写,以免影响结果。

所得到的访问文件是:/nginx/html/index.htm 或者 /nginx/html/index.html ;

  • 过程分析:

先进行等值匹配,因为访问的url是一个“/”,是个目录,所以nginx内部会发送一次请求,访问:http://localhost/index.htm (若访问不到,会访问第二个文件index.html);

内部访问不会再走这个已经匹配了的等值location,会访问默认目录,在默认目录 /nginx/html 下查找 index.htm文件;

参考文章

nginx官网server配置:https://www.nginx.com/resources/wiki/start/topics/examples/server_blocks/#a-default-catch-all-server-block