1、rewrite语法:指令语法:rewrite regex replacement[flag];
默认值:none
应用位置:server、location、if
ewrite是实现URL重定向的重要指令,他根据regex(正则表达式)来匹配内容跳转到replacement,结尾是flag标记
简单的小例子:(推荐学习:nginx教程)rewrite ^/(.*) http://www.baidu.com/ permanent; # 匹配成功后跳转到百度,执行永久301跳转
常用正则表达式:字符描述
\将后面接着的字符标记为一个特殊字符或者一个原义字符或一个向后引用
^匹配输入字符串的起始位置
$匹配输入字符串的结束位置
*匹配前面的字符零次或者多次
+匹配前面字符串一次或者多次
?匹配前面字符串的零次或者一次
.匹配除“\n”之外的所有单个字符
(pattern)匹配括号内的pattern
rewrite 最后一项flag参数:标记符号说明
last本条规则匹配完成后继续向下匹配新的location URI规则
break本条规则匹配完成后终止,不在匹配任何规则
redirect返回302临时重定向
permanent返回301永久重定向
2、应用场景:调整用户浏览的URL,看起来规范
为了让搜索引擎收录网站内容,让用户体验更好
网站更换新域名后
根据特殊的变量、目录、客户端信息进行跳转
3、常用301跳转:
之前我们通过用起别名的方式做到了不同地址访问同一个虚拟主机的资源,现在我们可以用一个更好的方式做到这一点,那就是跳转的方法
还是用www.brian.com虚拟主机为例子,修改配置文件brian.conf:[root@Nginx www_date]# cat brian.conf
server { # 添加个server区块做跳转
listen 80;
server_name brian.com;
rewrite ^/(.*) http://www.brian.com/$1 permanent; }
server {
listen 80;
server_name www.brian.com;
location / {
root html/brian;
index index.html index.htm;
}
access_log logs/brian.log main gzip buffer=128k flush=5s;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
检查语法:[root@Nginx conf]# ../sbin/nginx -t
nginx: the configuration file /opt/nginx//conf/nginx.conf syntax is oknginx: configuration file /opt/nginx//conf/nginx.conf test is successful
平滑重启:[root@Nginx conf]# ../sbin/nginx -s reload
windows测试效果:
4、域名跳转:
我们不仅可以做相同虚拟主机的资源域名跳转,也能做不同虚拟主机的域名跳转,我们下面就跳转下当访问brian.com域名的时候跳转到www.baidu.com的页面:
修改www.brian.com虚拟主机的brian.conf配置文件:[root@Nginx www_date]# cat brian.conf
server {
listen 80;
server_name brian.com;
location / {
root html/brian;
index index.html index.htm;
} if ( $http_host ~* "^(.*)") {
set $domain $1;
rewrite ^(.*) http://www.baidu.com break; }
access_log logs/brian.log main gzip buffer=128k flush=5s;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
windows测试:(访问brian.com 跳转到了www.baidu.com)