Nginx Rewrite (Nginx URL 重写)

简介: 实现网站的跳转,例如用户访问q.com,将其跳转到v.com。
语法: rewrite 正则表达式 替代内容 标记;
permanent URL永久重定向
break 在本条规则匹配完成后,停止匹配,不再做后续的匹配。
last 在本条rewrite规则执行完后,会对其所在的server { … } 标签重新发起请求;
示例1: 用户访问http://192.168.246.149/abc/a/1.html地址时,通过rewrite重定向值http://192.168.246.149/c/b/2.html

mkdir /usr/share/nginx/html/c/b -p    //创建目录
echo “/usr/share/nginx/html/c/b/2.heml” > /usr/share/nginx/html/c/b/2.html  //在2.html中写入显示内容
vim /etc/nginx/conf.d/default.conf   //向Nginx子配置文件中的server中写入以下内容
server {								
location /abc {							//当用户访问http://192.168.246.149/abc时网页自动跳转
rewrite .* /c/b/2.html permanent;		//rewrite为重写,.*为任意字符,表示将只要输入的地址前缀为http://192.168.246.149/abc(后可跟/1.html)都会跳转到http://192.168.246.149/c/b/2.html,permanent将地址显示为新的URL地址。
}
}

示例2: 利用正则中的“()”,替换url中一部分的内容:将http://192.168.246.149/2019/a/b/c/1.html换为http://192.168.246.149/2020/a/b/c/1.html

[root@localhost html]# mkdir 2020
[root@localhost html]# vim 2020/1.html
2020
[root@localhost html]# vim /etc/nginx/conf.d/default.conf 
 location /2019 {
        rewrite ^/2019/(.*)$ /2020/$1 permanent;		//$1表示前面()里的部分内容
        }
[root@localhost html]# systemctl restart nginx
在浏览器中访问http://192.168.246.149/2019/1.html

示例3: locatiton{rewrite}只能替换URL中的目录路径,使用if(){rewrite}可以替换协议主机目录全部内容,将http://www.abc.com换http://jd.com

server {
 if ( $host ~* abc.com ){
        rewrite .* http://jd.com permanent;
 }
}
在客户端做域名解析,然后访问www.abc.com即可看到京东页面

示例4: 将http://www.abc.com/11.html换为http://aaa.com/11.html

延续上一个实验
准备新网站:aaa.com
新页面:11/html
配置地址重写:
server {
        if ( $host ~* abc.com ){
        rewrite .* http://www.aaa.com$request_uri permanent;
        }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值