nginx入门之location

nginx入门之location

一、匹配规则

location [= | ~ | ~* |^~] uri
{
    ....
}

匹配顺序:

  1. 记录标准uri最匹配的一个,=前缀的精确匹配,并停止搜索
  2. 接着正则uri匹配,匹配到,结束搜索,使用此location
  3. 如果正则匹配失败,用刚才记录的匹配度最高的location

规则:

=:用于标准uri  
~: 正则,区分大小写  
~*: 不区分大小写  
^~: 用于标准uri前,找到,立即使用此location,不使用正则  

示例:

location  = / {
  # 只匹配"/".
  [ configuration A ]
}
location  / {
  # 匹配任何请求,因为所有请求都是以"/"开始
  # 但是更长字符匹配或者正则表达式匹配会优先匹配
  [ configuration B ]
}
location ^~ /images/ {
  # 匹配任何以 /images/ 开始的请求,并停止匹配其它location
  [ configuration C ]
}
location ~* .(gif|jpg|jpeg)$ {
  # 匹配以 gif, jpg, or jpeg结尾的请求.
  # 但是所有 /images/ 目录的请求将由 [Configuration C]处理.   
  [ configuration D ]
}

请求URI例子:

/ -> 符合configuration A
/documents/document.html -> 符合configuration B
/images/1.gif -> 符合configuration C
/documents/1.jpg ->符合 configuration D

@location 示例

error_page 404 = @fetch;
location @fetch( proxy_pass <http://fetch>; )

二、 根目录 root path;

适用:http,server,location

location /data/ {
   root /locationtest1;
 }

如:接到/data/index.html的请求时,将在/locationtest1/data/目录下找index.html

更改路径

root目录也可以更改,使用alias

示例:

location ~ ^/data/(.+.(html|htm))$ {
  alias /locationtest1/other/$1;
}

接到/data/index.html的请求时,将在/locationtest1/other/目录下找index.html

三、 网站首页设置

location ~ ^/data/(.+)/web/ $ {
  index index.$1.html index.my.html index.html;
}

当请求为/data/test/web/时,匹配成功,会到/data/test/web/目录下依次匹配index.test.html,index.my.html,index.html

CONTENTS