一、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; } } |