【Nginx 学习 一】location指令详解

location

转发请求:
nginx接受到客户端的请求时,获取请求的url,和location的表达式进行匹配,然后转发请求

语法

1
2
3
location url表达式{
请求转发的目标
}

url表达式

通过指定模式来与客户端请求的URI相匹配,基本语法如下:location [=|~|~*|^~|@] pattern{……}

  • 没有修饰符 表示:必须以指定模式开始,如:
    1
    2
    /          请求的路径必须以/开头,就是根目录下的所有请求
    /nginx 请求的路径必须以/nginx开头,就是根目录下的nginx下的请求
    1
    2
    3
    4
    5
    6
    server {
      server_name baidu.com;
      location /abc {
        ……
      }
    }
    结果访问网站都可以,如下:
    1
    2
    3
    4
    http://baidu.com/abc
    http://baidu.com/abc?p1
    http://baidu.com/abc/
    http://baidu.com/abcde
  • =表示:必须与指定的pattern模式精确匹配
    1
    2
    = /abc              与url必须相等,只能匹配/abc
    = /nginx/1.html 与url必须相等,只能匹配/nginx/1.html
    示例:
    1
    2
    3
    4
    5
    6
    server {
    server_name baidu.com;
      location = /abc {
        ……
      }
    }
    那么,如下是对的:
    1
    2
    http://baidu.com/abc
    http://baidu.com/abc?p1

如下是错的:

1
2
http://baidu.com/abc/
http://baidu.com/abcde
  • ~表示:指定的正则表达式要区分大小写
    1
    ~ /nginx            请求的路径必须以/nginx开头,而且区分大小写,不匹配/Nginx

示例:

1
2
3
4
5
6
server {
server_name baidu.com;
  location ~ ^/abc$ {
    ……
  }
}

那么,如下是对的:

1
2
http://baidu.com/abc
http://baidu.com/abc?p1=11&p2=22

如下是错的:

1
2
3
http://baidu.com/ABC
http://baidu.com/abc/
http://baidu.com/abcde
  • ~* 表示:指定的正则表达式不区分大小写
    1
    ~* /nginx     请求的路径必须以/nginx开头,可以匹配/Nginx

示例:

1
2
3
4
5
6
server {
server_name baidu.com;
location ~* ^/abc$ {
    ……
  }
}

那么,如下是对的:

1
2
3
http://baidu.com/abc
http://baidu..com/ABC
http://baidu..com/abc?p1=11&p2=22

如下是错的:

1
2
http://baidu..com/abc/
http://baidu..com/abcde
  • ^~ 类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,那么就停止搜索其他模式了

  • ......$表示以什么结尾

location的优先级

同时可以配置多个location,但是urllocation匹配如何优先级

location的优先级和配置的先后顺序无关,优先级如下:

  1. 带有=的精确匹配优先
  2. 没有修饰符的精确匹配
  3. 正则表达式按照他们在配置文件中定义的顺序
  4. 带有^~修饰符的,开头匹配
  5. 带有~~*修饰符的,如果正则表达式与URI匹配
  6. 没有修饰符的,如果指定字符串与URI开头匹配

Location区段匹配示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
location = / {
  # 只匹配 / 的查询.
  [ configuration A ]
}
location / {
  # 匹配任何以 / 开始的查询,但是正则表达式与一些较长的字符串将被首先匹配。
  [ configuration B ]
}
location ^~ /images/ {
  # 匹配任何以 /images/ 开始的查询并且停止搜索,不检查正则表达式。
  [ configuration C ]
}
location ~* \.(gif|jpg|jpeg)$ {
  # 匹配任何以gif, jpg, or jpeg结尾的文件,但是所有 /images/ 目录的请求将在Configuration C中处
  理。
  [ configuration D ]
} 各
请求的处理如下例:
■/ → configuration A
■/documents/document.html → configuration B
■/images/1.gif → configuration C
■/documents/1.jpg → configuration D

location和proxy_pass

1
2
3
4
5
6
server {
server_name localhost;
location /foo/ {
proxy_pass http://192.168.1.48:8081/;
}
}

请求的处理如下例:
客户端

1
http://localhost/foo/1.html

tomcat

1
http://localhost:8081/1.html