nginx重定向--rewrite重写功能介绍
rewrite只能放在server{},location{},if{}中,并且默认只能对域名后边的除去传递的参数外的字符串起作用,
例如 http://www.yang.com/abc/bbs/index.php?a=1&b=2 只对/abc/bbs/index.php重写。
1.先执行server块的rewrite
2.执行location里面定义的rewrite
3.选定location中的rewrite
- 语法格式:rewrite
[flag] -
正则表达式 -
:跳转内容或者路径 -
- [flag]:标志位 “标记”
-
- flag:表示支持rewrite的flag标记
-
- last:本条规则匹配完成后,继续向下匹配新的location URI规则
-
- rewrite zzr zzz last;
需求:www.kfc.com 公司业务变更,全部迁移到新的域名 www.benet.com代替,但是旧域名不能被废除,访问kfc可以跳转到benet,且匹配的uri不变。
vim /nginx.conf server { listen 80; server_name www.kfc.com; charset utf-8; location / { if ($host = 'www.kfc.com') { #$host为rewrite全局变量,代表请求主机头字段或主机名 rewrtie ^/(.*)$ http://www.benet.com/$1 permanent; "/" 后面所有的内容转换为 http://www.benet.com/$1 permanent; } root html; index index.html inde.htm }
访问域名一定要地址解析!!!!!!!!
echo '20.0.0.10 www.kfc.com www.bentet.com' >> /etc/hosts
给页面编写内容


此时访问 www.kfc.com 会自动跳转到 www.benet.com

公司业务新版本上线,用户访问网站同意显示在维护中,只有一个IP可以访问测试
vim /nginx.conf server { listen 80; server_name www.kfc.com; #域名修改 charset utf-8; #页面内容支持中文 set $rewrite true; #设置标记是否合法 if ( $remote_addr = "20.0.0.10") { #定义客户端的访问地址 set $rewrite false; #如果是20.0.0.10,则不重写(rewrite) } if ( $rewrite = true ) { rewrite (.+) /error.html redirect #如果不是20.0.0.10,则重写 #除了 20.0.0.10,其余都跳转error界面 } location / { if ($host = 'www.kfc.com') { rewrite ^/(.*)$ http://www.benet.com/$1 permanent; } root html; index index.html index.htm; }
进入error.html 编写内容


此时我们用另一台(20.0.0.20来访问)虚拟机测试

error,无法连接
- vim nginx.conf
-
- server {
- listen 80;
- server_name www.kfc.com;
- charset utf-8;
-
- location ~* /upload/.*\.php$ {
- 锁定 /upload以后的所有内容
- rewrite (.+) http://www.test.com permanent;
- 重写位 test.com
- }
- location / {
- root html;
- index index.html index.htm;
- }
- }

访问域名,一定要做域名解析!!!!

配置页面内容


访问内容正确