nginx config

nginx路由匹配规则

常见的路由匹配符号有:

  1. :精确匹配
  2. ^~:精确前缀匹配
  3. ~:区分大小写的正则匹配; ~*:不区分大小写的正则匹配
  4. /uri:普通前缀匹配
  5. /:通用匹配
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
location = / {
echo "规则A";
}
location = /login {
echo "规则B";
}
location ^~ /static/ {
echo "规则C";
}
location ^~ /static/files {
echo "规则X";
}
location ~ \.(gif|jpg|png|js|css)$ {
echo "规则D";
}
location ~* \.png$ {
echo "规则E";
}
location /img {
echo "规则Y";
}
location / {
echo "规则F";
}
请求URI 匹配路由规则
http://localhost/ 规则A
http://localhost/login 规则B
http://localhost/register 规则F
http://localhost/static/a.html 规则C
http://localhost/static/files/a.txt 规则X
http://localhost/a.png 规则D
http://localhost/a.PNG 规则E
http://localhost/img/a.gif 规则D
http://localhost/img/a.tiff 规则Y

同优先级精确度越高, 优先级越高

同级别的定义顺序越靠前, 优先级越高

反向代理配置

访问 http://xxx/a

1
2
3
location /a {
proxy_pass http://192.168.1.100:80;
}

转到了 http://192.168.1.100:80/a

1
2
3
location /a/ {
proxy_pass http://192.168.1.100:80/;
}

则转到了 http://192.168.1.100:80/, 注意规则里的两个/

负载均衡配置

1
2
3
4
5
6
7
8
9
upstream groups1 {
# 配置了不同权重
server 192.168.1.110:80 weight=10;
server 192.168.1.111:81 weight=3;
}

location /a/ {
proxy_pass http://groups1/;
}