Nginx的location配置

使用nginx的时候,免不了要给各种服务做代理,不同的规则要配置不同的location规则。

正则写法
  • 精确匹配

精确匹配 / ,主机名(域名)后面不能带任何的字符串

1
2
3
location = / {
configuration A # 配置项
}
  • 匹配所有请求

所有的请求地址都以 / 开头,这条规则就会匹配所有的请求,但是正则和最长的字符串会优先匹配到。

1
2
3
location / {
configuration B # 配置项
}
  • 匹配任何以 某字符串 开头

假如现在以 testimage 开头,匹配符合以后,还要继续往下搜索,只有后面的正则表达式没有匹配到时,这一条才会采用这一条。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
location /test/ {
configuration C # 配置项
}

location ~ /test/aaa {
configuration D # 配置项
}

# 匹配任何以 /image/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。
location ^~ /image/ {
configuration E # 配置项
}

# 字符匹配到 /image/,继续往下,会发现 ^~ 存在
location /image/ {
configuration F
}

# 最长字符匹配到 /image/abc,继续往下,会发现 ^~ 存在
# F与G的放置顺序是没有关系的
location /image/abc {
configuration G
}

# 只有去掉 config E 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用
location ~ /image/abc/ {
configuration H
}

location ~* /js/.*/\.js
  • 匹配不同文件结尾

一般将静态资源放到nginx中代理出来,有一些文件 .png、.jpg 需要单独配置规则

1
2
3
4
5
# 匹配所有以 gif,jpg或jpeg 结尾的请求
# 然而,所有请求 /image/ 下的图片会被 config E 处理,因为 ^~ 到达不了这一条正则
location ~* \.(gif|jpg|jpeg)$ {
configuration I
}
  1. = 开头表示精确匹配
    如 A 中只匹配根目录结尾的请求,后面不能带任何字符串。

  2. ^~ 开头表示uri以某个常规字符串开头,不是正则匹配

  3. ~ 开头表示区分大小写的正则匹配;

  4. ~* 开头表示不区分大小写的正则匹配

  5. / 通用匹配, 如果没有其它匹配,任何请求都会匹配到

顺序

(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)

匹配结果

上面的匹配结果,按照上面的location写法,以下的匹配示例成立:

  1. / -> config A

    精确完全匹配,即使/index.html也匹配不了

  2. /downloads/download.html -> config B

    匹配B以后,往下没有任何匹配,采用B

  3. /image/1.gif -> configuration E

    匹配到F,往下匹配到E,停止往下

  4. /image/abc/def -> config E

    最长匹配到G,往下匹配D,停止往下你可以看到 任何以/image/开头的都会匹配到D并停止,F G写在这里是有任何意义的,H是永远轮不到的,这里只是为了说明匹配顺序

  5. /documents/document.html -> config C

    匹配到C,往下没有任何匹配,采用C

  6. /documents/1.jpg -> configuration I

    匹配到C,往下正则匹配到I

  7. /documents/Abc.jpg -> config D

    最长匹配到 C,往下正则顺序匹配到 D,不会往下到 I

参考:https://segmentfault.com/a/1190000002797606

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2020/04/13/nginx-location/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

在 Vue 中使用 Fabric.js