文章目录
一、概览
1、Rewrite跳转场景
- URL看起来更规范、合理
- 企业会将动态URL地址伪装成静态地址提供服务
- 网址换新域名后,让旧的访问跳转到新的域名上
- 服务端某些业务调整
2、Rewrite实际场景
1、Nginx跳转需求的实现方式
- 使用rewrite进行匹配跳转
- 使用if匹配全局变量后跳转
- 使用location匹配再跳转
2、rewrite放在server{}, if{}, location{} 段中
- location只对域名后边的除去传递参数外的字符串起作用
3、对域名或参数字符串
- 使用if全局变量匹配
- 使用proxy_pass反向代理
3、比较rewrite和location
1、相同点
- 都能实现跳转
2、不同点
- rewrite是在同一域名内更改获取资源的路径
- location是对一-类路径做控制访问或反向代理,还可以proxy_ pass到其他机器
3、rewrite会写在location里,执行顺序
- 执行server块里面的rewrite指令
- 执行location匹配
- 执行选定的location中的rewrite指令
4、location优先级规则
1、匹配某个具体文件
(location=完整路径) > (location ^~完整路径) > (location ~*完整路径) > (location ~完整路径) > (location完整路径) >(location /)
2、用目录做匹配访问某个文件人
(location=目录) > (location ^~且录/) > (location~目录) >(location~*目录) > (location目录) > (location /)
二、实验
实验一、基于域名的跳转
实验需求
基于域名的跳转,现在公司旧域名www.kgc.com有业务需求有变更,需要使用新域名www.newkgc.com代替,但是旧域名不能废除,需要跳转到新域名上,而且后面的参数保持不变。
实验步骤
1、安装nginx及DNS
rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
yum install nginx -y
yum install bind -y
配置DNS并配置两个域名
www.kgc.com
www.newkgc.com
2、编辑配置文件
vim /etc/nginx/conf.d/default.conf
3、启动服务
systemctl start named
systemctl start nginx
4、网页访问测试
地址访问:www.newkgc.com
实验二、基于客户端IP访问跳转
实验需求
今天公司业务版本上线,所有IP访问任何内容都显示一个固定维护页面,只有公司IP访问正常
实验步骤
1、编辑配置文件
vim /etc/nginx/conf.d/default.conf
文件新增内容如下所示
set $rewrite true;
if ($remote_addr = “192.168.235.100”) {
set $rewrite false;
}
if ($rewrite = true) {
rewrite (.+) /main.html;
}
location = /main.html {
root /usr/share/nginx/html;
}
2、关闭防火墙并重启
iptables -F
setenforce 0
systemctl restart nginx
3、修改界面文件用来测试
cd /usr/share/nginx/html/
ls
cp -p index.html main.html
vim main.html
4、界面访问测试
www.kgc.com
实验三、基于旧、新域名跳转并加目录
实验需求
将域名http://bbs.kgc.com下面的发帖都跳转到http://www.kgc.com/bbs,且域名跳转后保持参数不变
实验步骤
1、dns配置文件修改
cd ~
cd /var/named/
ls
vim kgc.com.zone
2、重启DNS服务
systemctl restart named
3、编辑nginx配置文件
vim /etc/nginx/conf.d/default.conf
4、重启nginx服务
systemctl restart nginx
5、访问测试
客户机设置域名地址:echo “nameserver 192.168.235.151” > /etc/resolv.conf
浏览器访问地址:bbs.kgc.com/post/1.html
自动跳转到地址:www.kgc.com/post/1.html
实验四、基于参数匹配的跳转
实验需求
基于参数匹配的跳转,例如现在访问http://www.kgc.com/100-(100|200)-100.html跳转到http://www.kgc.com页面。
实验步骤
1、编辑配置文件
vim /etc/nginx/conf.d/default.conf
2、重启服务
systemctl restart nginx
3、访问测试
访问地址:www.kgc.com/100-100-100.html,界面自动跳转到:www.kgc.com
实验五、基于目录下所有php文件的跳转
实验需求
访问http://www.kgc.com/upload/1.php跳转到首页
实验步骤
1、编辑配置文件
vim /etc/nginx/conf.d/default.conf
2、重启服务
systemctl restart nginx
3、访问测试
访问地址为:www.kgc.com/upload/1.php,界面自动跳转到主页:www.kgc.com
实验六、基于最普通url请求的跳转
实验需求
要求:访问一个具体的页面跳转到首页
验证:浏览器访问http://www.kgc.com/abc/test.html跳转到首页
实验步骤
1、编辑配置文件
vim /etc/nginx/conf.d/default.conf
2、重启服务
systemctl restart nginx
3、访问测试
访问地址为:www.kgc.com/abc/test.html,界面自动跳转到主页:www.kgc.com