一、location配置匹配分类
1.字符串匹配
=
、^~
、@
和无任何前缀的字符串都属于字符串匹配location,@主要
用作nginx内部的一种转发行为
2.正则表达式匹配
~
、 ~*、
为正则匹配location
二、location匹配命令解释
nginx环境:http://192.168.13.101:8091/
命令 | 解释 | 匹配顺序优先级 | 配置举例 | 验证 |
= | 精确匹配字符串 | 1首先,精确匹配 匹配完成uri路径 匹配后则停止其他匹配 | location =/fd{ return 666; } | 访问htpp://192.168.13.101:8091/fd 则返回状态码666 |
^~ | 表示普通字符匹配 | 2其次,匹配 匹配前半uri路径 匹配后则停止其他匹配 | location ^~ /wds/ { return 666; } | 访问htpp://192.168.13.101:8091/wds/** 则返回状态码666 |
@ | 定义一个命名的 location使用在内部定向时,例如 error_page, try_files | error_page 404 = @fetch; location @fetch{ | 访问http://192.168.13.101:8091/wds/11.jpg 当11.jpg不存在的时候,原本nginx自带的404页面将不会显示,而是内部转发到http://static | |
无修饰前缀字符串 | 没有修饰符的uri前缀字符串匹配 | 4再匹配不带修饰前缀的字符串 遵循最大字符串匹配原则,直到uri中最大能匹配到的就停止匹配 | location /aaa/ { location /aaa/bb/ { | 1.访问htpp://192.168.13.101:8091/aaa/** 则返回状态码666 2.访问htpp://192.168.13.101:8091/aaa/bb/ 则返回状态码777 |
~ | 区分大小的正则匹配 | 3按配置文件中顺序的正则匹配 匹配到一个正则就停止匹配 | location ~ \.(gif|jpg)$ { return 666; } | 1.访问http://192.168.13.101:8091/*.jpg 则返回状态码666 2.访问http://192.168.13.101:8091/*.JPG 则返回状态码404 请求不到 |
~* | 不区分大小的正则匹配 | 3按配置文件中顺序的正则匹配 匹配到一个正则就停止匹配 | location ~* \.(gif|jpg)$ { return 666; } | 1.访问http://192.168.13.101:8091/*.jpg 则返回状态码666 2.访问http://192.168.13.101:8091/*.GIF 则返回状态码666 |
/ | 通用匹配,任何请求都会匹配到 | 5最后通配匹配 | location / { return 777; } | 访问http://192.168.13.101:8091/sddws 则返回状态码777 都匹配不到的时候最后匹配到 / |
综上:大致优先级如下:
(=)>(^~)>(~)或(~*)>(无修饰前缀字符)>(/)
~和~* 正则匹配顺序,以配置文件中先后顺序进行匹配,先命中到就停止其他匹配,否则继续匹配正则。
最大字符串匹配:是指能匹配到的最大长度字符串。
匹配命中结果特殊说明:
1、在匹配到无修饰前缀字符后,会将结果临时保存起来,继续匹配正则表达式,如果能命中,则会将使用新的
正则结果,若不能命中,才会使用前面保存的结果;
2、^~匹配命中后将当前作为结果并停止其他匹配;=匹配命中后将当前作为结果并停止其他匹配;
3、/ 通配匹配,在其他匹配都不命中时,作为结果;=/ 严格匹配,必须是http://ip:port/ 才能命中,并将当前作为结果停止其他匹配。
常用正则表达式:
- . : 匹配除换行符外的任意字符
- ? : 重复0次或1次
- +: 重复1次或更多次
- *: 重复0次或更多次
- d :匹配数字
- ^ : 匹配字符串的开始
- $ : 匹配字符串的结束
- {n} : 重复n次
- {n,} : 重复n次或更多次
- [c] : 匹配单个字符,如此处的字符 c
- [a-z] : 匹配a-z小写字母的任意一个
- (a|b|c):匹配a或b或c</span>
三、场景配置
1、静态服务
#前端访问http://192.168.56.88:8080/statics/11.jpg
#就会访问/home/duke/statics/11.jpg
#启动nginx的用户账号必须拥有/home/duke/statics/11.jpg 该文件及其所属目录的访问权限,否则报错403
location /statics/{
root /home/duke;
autoindex on;#自动列出文件
autoindex_exact_size on;#精确列表显示文件格式,包括大小 kb mb gb
autoindex_localtime on;#显示文件时间
#limit_rate 1k;#指定每秒该连接能下载的bytes,主要用来限制个别请求的带宽
auth_basic string;
}
四、路径替换
需求:访问 http://192.168.16.255:8181/welcome/hello 转发到 http://192.168.16.123:7898/welcome-new/hello
本机ip端口是192.168.16.255:8181
location /welcome/ {
root html;
index index.html index.htm;
proxy_pass http://192.168.16.123:7898/welcome-new/;
}
或负载
upstream server_new {
ip_hash;
server 192.168.16.123:7898 max_fails=3 fail_timeout=45s;
server 192.168.16.123:7877 max_fails=3 fail_timeout=45s;
}
location /welcome/ {
root html;
index index.html index.htm;
proxy_pass http://server_new/welcome-new/;
}
上述匹配是会将 路径中 welcome 替换成 welcome-new