重定向
Rewrite规则
rewrite功能就是,使用nginx提供的全局变量或自己设置的变量,结合正则表达式和标志位实现url重写以及重定向。rewrite只能放在server{},location{},if{}中,并且只能对域名后边的除去传递的参数外的字符串起作用,例如 http://seanlook.com/a/we/index.php?id=1&u=str 只对
/a/we/index.php
重写。
语法rewrite regex replacement [flag];
如果相对域名或参数字符串起作用,可以使用全局变量匹配,也可以使用proxy_pass反向代理。
表明看rewrite和location功能有点像,都能实现跳转,主要区别在于rewrite是在同一域名内更改获取资源的路径,而location是对一类路径做控制访问或反向代理,可以proxy_pass到其他机器。很多情况下rewrite也会写在location里,它们的执行顺序是:
- 执行server块的rewrite指令
- 执行location匹配
- 执行选定的location中的rewrite指令
如果其中某步URI被重写,则重新循环执行1-3,直到找到真实存在的文件;循环超过10次,则返回500 Internal Server Error错误。
正则表达式
由于重写是对域名之后的部分,所以正则匹配也是从这里开始。
比如http://baidu.com/hello/xxx/yyy
, 是从/hello/xxx/yyy
开始匹配。
^/(.*)
匹配域名后的任意内容,其中(.*)
将匹配到的内容提取到变量中,(.*)
可以多个,依次提取到变量$1
、$2
...中。
比如http://baidu.com/hello/xxx/yyy
,^/(.*)
提取到$1,值为hello/xxx/yyy
应用例子1:http://baidu.com/hello/xxx/yyy
`rewrite ^(/hello/.*) http://baidu.com/sss/$1 permanent;`
将http://baidu.com/hello/xxx/yyy
重定向到http://baidu.com/sss/hello/xxx/yyy
应用例子2:
`rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;`
如果请求为/download/eva/media/op1.mp3
则请求被rewrite到/download/eva/mp3/op1.mp3
其中.mp3
的.
用了转义字符\
,即\.
。
反向代理
核心配置:
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://Demo_server; # 反向代理地址
}
完整例子
upstream my_servers {
ip_hash; # 将相同ip的请求发送到同个server上
server localhost:88; # 配置多个,实现轮询,将多个前端请求自动分配到多个server上
}
server {
listen 80;
server_name demo.com;
rewrite ^(/xxx/.*) http://demo.com/sss/$1 permanent;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://my_servers; # 反向代理地址
}
}
将所有http://demo.com/xxx/...
的请求,先重定向为http://demo.com/sss/xxx/...
;
再反向代理给本地tomcat服务器,tomcat http端口为88
。