location匹配符号规则
= 精确匹配
如: =/123 如果写全那就是: www.chenleilei.net/123
~ 模糊匹配(区分大小写)
~* 模糊匹配(不区分大小写,一般用这个)
^~ 不用正则表达式,只匹配常规字符. 优先匹配.
匹配实验:
vim nginx.conf
#---------------------------------------------
server {
serve;r_name www.leilei.com;
root html/www;
index inde.html index.htm;
#实验1
location / {
return 401;
}
#实验2
location = / {
return 402;
}
#实验3
location /doc/ {
return 301;
}
#实验4
location ^~ /images/ {
return 404;
}
#实验5
location ~* \.(gif|jpg|jpeg) {
return 500;
}
}
#---------------------------------------------
访问测试1 :
[root@nginx-test nginx]# curl -I 10.0.0.70
HTTP/1.1 402 Payment Required # 匹配了 "实验2" ,也就是说 = 是精准匹配,他优先级高于所有
Server: nginx/1.16.1
Date: Fri, 03 Jan 2020 09:24:23 GMT
Content-Type: text/html
Content-Length: 167
Connection: keep-alive
结论: = 优先级 1
访问测试2 : location /doc/
[root@nginx-test nginx]# curl -I 10.0.0.70/doc/
HTTP/1.1 403 Forbidden # 匹配了 "实验3" 他的优先级第二
Server: nginx/1.16.1
Date: Fri, 03 Jan 2020 09:27:03 GMT
Content-Type: text/html
Content-Length: 153
Connection: keep-alive
访问测试3: location ^~ /images/
在 /images/ 创建 1.jpg
[root@nginx-test nginx]# curl -I 10.0.0.70/images/
HTTP/1.1 301 Moved Permanently ## 如果这里面没有这个目录是不会显示301,而显示404,但是这里显示的就是
Server: nginx/1.16.1 ## 301,说明规则生效了
Date: Fri, 03 Jan 2020 09:37:14 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location:
访问测试4: location / {
#访问一个不存在的页面 出现401
[root@nginx-test nginx]# curl -I 10.0.0.70/q.html
HTTP/1.1 401 Unauthorized
Server: nginx/1.16.1
Date: Fri, 03 Jan 2020 09:50:54 GMT
Content-Type: text/html
Content-Length: 179
Connection: keep-alive
当不匹配所有的时候,他会匹配 /
从实验得出权重顺序:
= 优先级最高 1
^~ 优先级 2
/doc/ 优先级3
~ 优先级3 模糊匹配(区分大小写)
~* 优先级3 模糊匹配(不区分大小写)
/ 优先级4 所以规则都不匹配是,默认匹配.
rewrite 正则讲解:
rewrite ^/(.*) www.baidu.com/$1 permanent;
^/(.*) 这是和sed正则取IP是一个意思,后面的 $1
取IP:
[root@nginx-test nginx]# ifconfig eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.0.70 netmask 255.255.255.0 broadcast 10.0.0.255
inet6 fe80::20c:29ff:fe48:a0ce prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:48:a0:ce txqueuelen 1000 (Ethernet)
RX packets 6301 bytes 603407 (589.2 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 4527 bytes 584730 (571.0 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
[root@nginx-test nginx]# ifconfig eth0 | sed -nr 's#^.*inet (.*) netma.*$#\1#gp'
10.0.0.70
取多个:
[root@nginx-test nginx]# ifconfig eth0 | sed -nr 's#^.*inet (.*) .*netmask (.*) broa.*$#\1\n\2#gp'
10.0.0.70
255.255.255.0
http跳转的多种方法
第一种:
#添加一个跳转域名信息的虚拟主机
server {
listen 80;
server_name chenleilei.net;
rewrite ^/(.*) http://www.chenleilei.net/$1 permanent;
}
server {
listen 80;
server_name www.chenleilei.net;
root html;
index index.htm index.html index.php;
}
第二种:
#通过if指令来进行判断跳转
server {
listen 80;
server_name www.chenleilei.net;
root html/www;
index index.html index.php;
if ( $host ~* ^chenleilei.net$){
rewite ^/(.*) http://www.chenleilei.net/$1 permanent;
}
}

最后修改:2020-03-06 22:20:41
© 著作权归作者所有
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

发表评论