rewrite 用来实现URL重写以及重定向。通过nginx提供的全局变量或自己设置的变量,结合正则表达式和标记位进行重定向.
rewrite语法
格式: rewrite ${regex} ${replacement} [flag]
作用域: rewrite只能放在server{}, location{} 和 if{}中,并且默认只能对域名后边的路径起作用, 传递参数不变
例如rewrite http://www.baidu.com/tieba/bbs/index.html?a=1&b=2 时 , 只会对/tieba/bbs/index.html
进行重写, 而参数a=1&b=2
不变。
注意事项:
- 当location 中存在flag时,之后的 rewrite 指令集(包括 rewrite 和 return)都不会再执行。
- 当location中同时存在 rewrite 和 proxy_pass 时,若要使proxy_pass生效, rewrite必须使用 break 标记,否则proxy_pass将被跳过。
- 当location中同时存在 rewrite 和 proxy_pass 时,proxy_pass 中的 path 不会生效。
rewrite和proxy_pass的区别
proxy_pass主要应用于分发于后端的服务器,作为代理或者是负载均衡使用,在进行分发请求的时候,用户请求的URL不会发生变化,返回的状态码基本上都是200;
而rewrite主要用于访问资源路径的变化。一般用于以下2种场景:
- 需要捕捉URL路径中的特殊元素,但没有合适的Nginx全局变量来替换;
- 需要在路径中增加修改删除元素。
flag标记说明
flag标记 | 说 明 |
---|---|
last | 用 ${replacement} 部分进行新的 location 匹配; 浏览器地址栏的URL地址不变,但在服务器访问的程序及路径发生了变化 |
break | 在本条规则匹配完成后,终止匹配,不再匹配后面的规则; 浏览器地址栏的URL地址不变,但在服务器访问的程序及路径发生了变化 |
redirect | 返回 302 临时重定向, 浏览器地址会显示跳转后的URL地址 |
permanent | 返回 301 永久重定向, 浏览器地址会显示跳转后的URL地址 |
last和break标记的实现功能类似,但二者之间有细微的差别,使用alias指令时必须用last标记,使用proxy_pass指令时要使用break标记。
配置例子
例子1 rewrite使用友好路径传递参数
在使用rewrite的时候,用于正则表达式的匹配,从而设置比较灵活,如下使用友好的路径来处理传递的参数:
- 使用相对路径进行匹配
rewrite ^/listings/(.*)$ /listing.html?listing=$1 last;
- 使用绝对路径进行匹配
rewrite ^/listings/(.*)$ http://mysite.com/listing.html?listing=$1 last;
如上的规则主要是将http://mysite.com/listings/123
重写到http://mysite.com/listing.html?listing=123
,从而让listing.html来处理相关参数
例子2 http永久重定向到https
在使用永久重定向的时候,最好的方法是使用return。因为使用rewrite的时候,会进行正则表达式的匹配,从而会消耗速度,而使用return的时候可以直接返回永久重定向的结果。
- 使用return:
server {
listen 80;
server_name localhost;
return 301 https://www.kel.com/$request_uri;(使用return直接返回301永久重定向)
}
- 使用rewrite:
location / {
root html;
index index.html index.htm;
rewrite ^ https://www.kel.com$uri permanent;
}
例子3 添加移除www前缀
有些时候,需要使用或者不使用www前缀,如下配置:
server {
listen 80;
server_name localhost;
return 301 $schema://www.domain.com$request_uri;(添加www前缀)
return 301 $schema://domain.com$request_uri;(去除www前缀)
}
例子4 更换域名
有些时候,需要将旧域名更换为新域名,也可以使用return,如下所示:
server {
listen 80;
server_name www.old-name.com;
return 301 $schema://www.new-name.com$request_uri;
}
网友评论