重定向
Rewrite規(guī)則
rewrite功能就是,使用nginx提供的全局變量或自己設(shè)置的變量,結(jié)合正則表達(dá)式和標(biāo)志位實(shí)現(xiàn)url重寫(xiě)以及重定向。rewrite只能放在server{},location{},if{}中,并且只能對(duì)域名后邊的除去傳遞的參數(shù)外的字符串起作用,例如 http://seanlook.com/a/we/index.php?id=1&u=str 只對(duì)
/a/we/index.php重寫(xiě)。
語(yǔ)法rewrite regex replacement [flag];
如果相對(duì)域名或參數(shù)字符串起作用,可以使用全局變量匹配,也可以使用proxy_pass反向代理。
表明看rewrite和location功能有點(diǎn)像,都能實(shí)現(xiàn)跳轉(zhuǎn),主要區(qū)別在于rewrite是在同一域名內(nèi)更改獲取資源的路徑,而location是對(duì)一類(lèi)路徑做控制訪問(wèn)或反向代理,可以proxy_pass到其他機(jī)器。很多情況下rewrite也會(huì)寫(xiě)在location里,它們的執(zhí)行順序是:
- 執(zhí)行server塊的rewrite指令
- 執(zhí)行l(wèi)ocation匹配
- 執(zhí)行選定的location中的rewrite指令
如果其中某步URI被重寫(xiě),則重新循環(huán)執(zhí)行1-3,直到找到真實(shí)存在的文件;循環(huán)超過(guò)10次,則返回500 Internal Server Error錯(cuò)誤。
正則表達(dá)式

由于重寫(xiě)是對(duì)域名之后的部分,所以正則匹配也是從這里開(kāi)始。
比如http://baidu.com/hello/xxx/yyy, 是從/hello/xxx/yyy開(kāi)始匹配。
^/(.*) 匹配域名后的任意內(nèi)容,其中(.*)將匹配到的內(nèi)容提取到變量中,(.*)可以多個(gè),依次提取到變量$1、$2...中。
比如http://baidu.com/hello/xxx/yyy,^/(.*)提取到$1,值為hello/xxx/yyy
應(yīng)用例子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
應(yīng)用例子2:
`rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;`
如果請(qǐng)求為/download/eva/media/op1.mp3則請(qǐng)求被rewrite到/download/eva/mp3/op1.mp3
其中.mp3的.用了轉(zhuǎn)義字符\,即\.。
反向代理
核心配置:
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的請(qǐng)求發(fā)送到同個(gè)server上
server localhost:88; # 配置多個(gè),實(shí)現(xiàn)輪詢,將多個(gè)前端請(qǐng)求自動(dòng)分配到多個(gè)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/...的請(qǐng)求,先重定向?yàn)?code>http://demo.com/sss/xxx/...;
再反向代理給本地tomcat服務(wù)器,tomcat http端口為88。