nginx(四) : location 配置详解

location 介绍

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

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

location 的语法

location [=|~|~*|^~] patt {
}
- 中括号能够不写任何参数,此时称为通常匹配
- 也能够写参数

根据参数的特性,能够大体分为如下三种:java

location = patt {} [精准匹配]
location   patt {} [通常匹配]
location ~ patt {} [正则匹配]

location匹配规格介绍

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

三种匹配方式介绍

通常匹配
location  /{
   root /var/www/html/;
   index index.htm index.html;
}

注意:/ 后能够跟参数,记录最长的匹配结果。nginx

等值匹配
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.jpgurl

三个匹配优先级介绍

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

常见易错多location配置

等值与通常匹配同时使用

代码以下:code

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

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

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

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

  • 过程分析:

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

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

参考文章

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

相关文章
相关标签/搜索