Nginx高级技术: 地址重写 Rewrite和应用场景

一、rewrite 场景示例说明

1、基于客户端指定 IP 访问跳转

应用场景说明:指定的 IP地址能正常访问192.168.179.10访问正常。

Rewrite配置如下:

vim /usr/local/nginx/conf/nginx.conf
server {
    listen       80;
    server_name  www.old.com;     
    charset utf-8;
    access_log  /var/log/nginx/www.old.com-access.log;     

    #设置是否合法的ip地址标记
    set $rewrite true;                            #设置变量$rewrite,变量值为boole值true
    #判断是否为合法IP
    if ($remote_addr = "192.168.179.10"){   #当IP为192.168.179.10时,将变量值设为false,不进行重写。
        set $rewrite false;
    }
    #除了合法IP,非法IP访问,跳转维护页面
    if ($rewrite = true){                        #当变量值为true时,进行重写
        rewrite (.+) /weihu.html;           #将域名后边的路径重写成/weihu.html,例如www.kgc.com/weihu.html
    }
    location = /weihu.html {
        root /var/www/html;            #维护界面静态加载地址
    }
    
    location / {
        root   html;
        index  index.html index.htm;
    }
}

2、基于旧域名跳转到新域名上并同时在后面加访问目录

应用场景说明:旧地址访问的是 http://www.new.com/ceshi/,现在需要将这个域名下面的访问都跳转到新地址http://www.new.com/xinzeng/ceshi/

Rewrite配置如下:

vim /usr/local/nginx/conf/nginx.conf
server {
    listen       80;
    server_name  www.new.com;          
    charset utf-8;
    access_log  /var/log/nginx/www.new.com-access.log;
    #添加
    location /ceshi {
        rewrite (.+) http://www.new.com/xinzeng$1 permanent;      
    }
    
    location / {
        root   html;
        index  index.html index.htm;
    }
}

3、基于域名的访问跳转

应用场景说明: 现业务变更需要将旧域名www.old.com访问,跳转至新域名www.new.com上,但是旧域名不能废除,需要跳转到新域名上。

Rewrite配置如下:

vim /usr/local/nginx/conf/nginx.conf

server {
    listen       80;
    server_name  www.old.com;
    charset utf-8;
    access_log  /var/log/nginx/www.old.com.access.log;
    location / {
        if ($host = 'www.old.com'){


            rewrite ^/(.*)$ http://www.new.com/$1 permanent;
        }


        root   html;
        index  index.html index.htm;
    }
}

  • 22
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值