
1、rewrite语法:
指令语法:rewrite regex replacement[flag];默认值:none应用位置:server、location、ifewrite是实现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、应用场景:
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)


以上就是详细介绍Nginx的rewrite(地址重定向)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号