Nginx地址重写

Nginx地址重写
适用范围:
因域名地址可能会因为其他原因更换,而客户因为习惯之前域名,可能会难以适应,故需进行地址重写,可实现网页目录的跳转和域名的跳转,从而增加客户接受能力。

格式:
rewrite 旧地址 新地址 [选项]

1.修改配置文件
# vim /usr/local/nginx/conf/nginx.conf
.. ..
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
rewrite /a.html /b.html redirect; 【注意空格】
}
}

***** redirect 【可加可不加,添加后可以在地址栏上看到地址的跳转】

2.重起服务
# /usr/local/nginx/sbin/nginx -s reload


可利用正则进行设置

示例:

#access_log logs/host.access.log main;
rewrite ^/ http://www.baidu.com/; 【尖角号/ 为判断为包含/即可跳转】
location / {
root html;
index index.html index.htm;
# rewrite /a.html /b.html redirect;
}


二)实现跳转相同页面 【用户访问网页内容可得到相应内容】

1.修改配置文件:
#access_log logs/host.access.log main;
rewrite ^/(.*) http://www.baidu.com/&1;
location / {
root html;
index index.html index.htm;
# rewrite /a.html /b.html redirect;
}


(.*) 匹配所有【复制】
$1 粘贴

*********************************************************************************************************************


三)不同浏览器,访问相同页面,返回不同结果


1.需要准备两套页面
切换到存放网页的目录
# cd /usr/local/nginx/html

创建网页:
echo "curl" > test.html
mkdir firefox
echo "firefox" > firefox/test.html

2.修改配置文件
#access_log logs/host.access.log main;
#rewrite ^/(.*) http://www.tmooc.cn/&1;

if ($http_user_agent ~* firefox){ rewrite ^/(.*)$ /firefox/$1; 【首先用if语句对浏览器进行判断,然后确定是否对网页进行跳转】 【~* 为不区分大小写】
}
location / {
root html;
index index.html index.htm;
# rewrite /a.html /b.html redirect;
}

3.刷新服务

# /usr/local/nginx/sbin/nginx -s reload

4.测试

firefox 192.168.4.5/test.html
curl 192.168.4.5/test.html 【可以看到显示内容不同】



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值