Nginx : URL重定向

Nginx : URL重定向

URL 模块语法
1) set 设置变量
2) if 负责语句中的判断
3) return 返回返回值或URL
4) break 终止后续的rewrite规则
5) rewrite 重定向URL
set指令 自定义变量
Syntax:
set $variable value;
Default:
—
Context:
server, location, if
将http://www.ayitula.com 重写为 http://www.ayitula.com/baism
location / {
 set $name baism;
 rewrite ^(.*)$ http://www.ayitula.com/$name;
 }
if 指令 负责判断
Syntax:
if (condition) { ... }
Default:
—
Context:
server, location
location / {
 root html;
 index index.html index.htm;
 if ($http_user_agent ~* 'Chrome') {
 break;
 return 403;
 #return http://www.jd.com;
 }
 }
#模糊匹配 ~匹配 !~不匹配 ~* 不区分大小写的匹配
#精确匹配 = !=
return 指令 定义返回数据
Syntax: return code [text];
return code URL;
return URL;
Default: —
Context: server, location, if
location / {
 root html;
 index index.html index.htm;
 if ($http_user_agent ~* 'Chrome') {
 return 403;
 #return http://www.jd.com;
 }
 }
break 指令 停止执行当前虚拟主机的后续rewrite指令集
Syntax: break;
Default:—
Context:server, location, if
location / {
 root html;
 index index.html index.htm;
 if ($http_user_agent ~* 'Chrome') {
 break;
 return 403;
 }
 }
rewrite <regex> <replacement> [flag];
关键字 正则 替代内容 flag标记
flag:
last #本条规则匹配完成后,继续向下匹配新的location URI规则
break #本条规则匹配完成即终止,不再匹配后面的任何规则
redirect #返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent #返回301永久重定向,浏览器地址栏会显示跳转后的URL地址
域名跳转
www.ayitula.com 重写为 www.jd.com
server {
 listen 80;
 server_name www.ayitula.com;
 location / {
 rewrite ^/$ http://www.jd.com permanent ;

 }
}
注意:
重定向就是将网页自动转向重定向
301永久性重定向:新网址完全继承旧网址,旧网址的排名等完全清零
 301重定向是网页更改地址后对搜索引擎友好的最好方法,只要不是暂时搬移
的情况,都建议使用301来做转址。
302临时性重定向:对旧网址没有影响,但新网址不会有排名
 搜索引擎会抓取新的内容而保留旧的网址
break 类似临时重定向
根据用户浏览器重写访问目录
如果是chrome浏览器 就将 http://192.168.10.42/$URI 重写为
http://http://192.168.10.42/chrome/$URI
实现 步骤
1)URL重写
2)请求转给本机location
location / {
.....
if ($http_user_agent ~* 'chrome'){
 #^ 以什么开头 ^a
 #$ 以什么结尾 c$
 #. 除了回车以外的任意一个字符
 #* 前面的字符可以出现多次或者不出现
 #更多内容看正则表达式 re
 rewrite ^(.*)$ /chrome/$1 last;
 }
 location /chrome {
 root html ;
 index index.html;
 }
}
url重写后,马上发起一个新的请求,再次进入server块,重试location匹配,超过
10次匹配不到报500错误,地址栏url不变
last 一般出现在server或if中
数据包走向 client-->nginx nginx告诉客户端让服务器的新地址(真实服务器),
客户端收到后再去找服务器 client--->server
作业
 # 访问 /baism00.html 的时候,页面内容重写到 /index.html 中
 rewrite /baism00.html /index.html last;
 # 访问 /baism01.html 的时候,页面内容重写到 /index.html 中,并停止后
续的匹配
 rewrite /baism01.html /index.html break;
 # 访问 /baism02.html 的时候,页面直接302定向到 /index.html中
 rewrite /baism02.html /index.html redirect;
 # 访问 /baism03.html 的时候,页面直接301定向到 /index.html中
 rewrite /baism03.html /index.html permanent;
 # 把 /html/*.html => /post/*.html ,301定向
 rewrite ^/html/(.+?).html$ /post/$1.html permanent;
 # 把 /search/key => /search.html?keyword=key
 rewrite ^/search/([^/]+?)(/|$) /search.html?keyword=$1 permanent;
原文地址:https://www.cnblogs.com/hanfe1/p/13625609.html