一、基本规则
1.Location分类
location可以分为三类:
location = 精准匹配
location 一般匹配
location ~ 正则匹配
备注:
~ : 区分大小写
~*:不区分大小写
!~: 区分大小写不匹配
!~* : 不区分大小写不匹配
^~ : 普通字符匹配,使用前缀匹配。匹配成功,不在进行匹配规则
= : 精准匹配
案例分析:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
root /var/www/html/aaa;
index index.html aaa.html;
}
location = /index.html {
root /var/www/html/bbb;
index index.html;
}
location ~ /INDEX.html {
root /var/www/html;
index indec.html INDEX.html;
}
[root@localhost ~]# cd /usr/local/nginx/
[root@localhost html]# mkdir aaa
[root@localhost html]# mkdir bbb
[root@localhost html]# mkdir ccc
[root@localhost html]# echo "abc">/aaa.html
[root@localhost html]# echo "bbb">/index.html
[root@localhost html]# echo "ccc">/INDEX.html
[root@localhost html]# systemctl start nginx
2.Location 优先级
= 优先级最高,匹配成功,不再进行匹配其他
^~ 匹配成功,不再进行匹配其他
~和~* 正则表达式,优先级次之
/ 通用匹配,任何请求都可以匹配
总结:
(location =)> (location ^ ~) > ( location ~) > ( location ~*) > ( location ) > ( location / )
二、示例分析
(1)基于域名跳转
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
root html;
index index.html index.htm;
if ($host = 'www.benet.com')
{
rewrite ^/(.*)$ http://www.accp.com/$1 permanent;
}
备注:
$host = 'www.benet.com' 判断获取到得请求URL是否为www.benet.com
=号两边有空格
permanent:返回 301 永久重定向,浏览器地址栏会显示跳转后的 URL 地址,爬虫更新 url,没有则返回302。
^/(.*)$
^ 指的是以任何字符或字符串开始的域名都会匹配上
/ 指得是url后跟的/,比如www.benet.com/index.html
.* 匹配任意多个字符,注意这里的(),括号里的内容会用后面的$1调用
$ 结尾
(2)基于客户端IP访问跳转
(3)基于旧域名跳转到新域名
(4)基于参数匹配跳转
(5)基于php文件跳转
(6)基于url请求跳转