本文主要介绍Rewrite如何跳转,和基于跳转我们可以做哪些操作,
如:维护企业页面时。企业旧域名更改新域名,如何旧域名跳转到新域名…
一,Rewrite跳转场景
- URL看起来更规范,合理
- 企业会将动态URL地址伪装成静态地址提供服务
- 网站换新域名后,让旧的访问跳转到新的域名上
- 服务端某些业务的调整
二, Rwrite跳转需求的实现方式
- Nginx跳转需求的实现方式
rewrite进行匹配跳转
if匹配全局变量后跳转
location匹配再跳转 - rewrite放在server{} ,if{}, location{}段中
location只对域名后边的出去传递参数外的字符串起作用 - 对域名或参数字符串
使用if全局变量匹配
使用proxy_pass反向代理
三,命令语法
rewrite <regex> <rplacement> [flag];
正则 跳转后的内容 rewrite支持的flag标记
四,location的分类
分类:
location = patt {} 精准匹配
location patt {} 一般匹配
location ~ patt {} 正则匹配
五,location优先级
1.=类型
2^~类型表达式
3.正则表达式(和*)类型
4.常规字符串匹配类型,按前缀匹配
5.通用匹配(/),如果没有其他匹配,任何请求都会匹配到
5.1比较rewrite和location
相同点
- 都能实现跳转
不同点 - rewrite是在同一域名内更改获取资源的路径
- location是对一类路径做控制访问或反向代理,还可以
proxy_pass到其他机器
rewrite会写在location里,执行顺序 - 执行server块里面的rewrite指令
- 执行location匹配
- 执行选定的location中的rewrite指令
六,实现跳转
1.基于域名跳转
步骤一.开局的nginx配置:
vi /usr/local/nginx/conf/nginx.conf
在server段内添加跳转:
location / {
#root html;
#index index.html index.htm;
if ($host = 'www.as.top') {
rewrite ^/(.*)$ http://www.hgg.top permanent;
}
}
2.保存,验证配置文件语法
nginx -t
步骤二:重启服务nginx验证
重启服务;
systemctl restart nginx
浏览器:输入旧域名www.as.top—自动跳转新域名www.hgg.top
抓包研究:
2.基于ip访问跳转;(用于维护网页时,维护企业网站操作!)
步骤一:nginx.conf添加配置;
vi /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.as.top;
charset utf-8;
access_log /var/log/nginx/www.as.top.accesss.log;
set $rewrite ture;
if ($remote_addr = '20.0.0.1') {
set $rewrite false;
}
if ($rewrite = ture) {
rewrite (.+) /wh.html;
}
location = /wh.html {
root /usr/local/nginx/html/;
}
location / {
root html;
index index.html index.htm;
}
步骤二:重启服务验证!
管理员ip(允许的ip):
20.0.0.1的ip登录的话,可以正常访问网页!
其他ip:
显示咱们之前指定跳转的wh.html 网页文档!!!
3.基于旧域名跳转到新域名后面目录
步骤一:在旧域名nginx配置文件中添加,跳转;
vi /usr/local/nginx/conf/nginx.conf
server模块下:
location /post { #一般匹配/post匹配条件
#root html;
#index index.html index.htm;
rewrite (.+) http://www.hgg.top/bbs$1 permanent;
}
步骤二:重启服务验证
重启服务
输入www.as.top/post 旧域名文件
说明:因为新域名bbs目录下咱们没有创建,所以显示不出来,但是可以看到网页已经跳转了;
4.基于参数配置跳转
步骤一:在旧域名nginx配置文件中添加,跳转;
vi /usr/local/nginx/conf/nginx.conf
在server段内,访问日志下行添加;
if ($request_uri ~ ^/100-(100|200)-(\d+).html$) {
rewrite (.*) http://www.hgg.top permanent;
}
步骤二:重启服务验证
输入www.as.top/100-或者100|200-和任意数字.html
验证:输入–www.as.top/100-100-100.html
5.基于目录下所有php结尾的文件跳转
步骤一:在旧域名nginx配置文件中添加,跳转;
vi /usr/local/nginx/conf/nginx.conf
在server段内:
location ~* /upload/.*\.php$ {
rewrite (.+) http://www.hgg.top permanent;
}
验证语法:nginx -t
步骤二:重启服务nginx验证登录
重启服务;
输入www.as.top/upload/1.php
www.as.top/upload/as.php
6.基于最普通的一条URL请求跳转
步骤一:在旧域名nginx配置文件中添加,跳转;
vi /usr/local/nginx/conf/nginx.conf
location ~* /1/as.html {
rewrite (.+) http://www.hgg.top permanent;
}
步骤二:重启服务验证登录
重启服务
验证登录:输入www.as.top/1/as.html