在Nginx中實現重定向可以通過rewrite指令,具體可參考《Nginx學習——http_rewrite_module的rewrite指令》
通過Lua模塊也可以實現同樣的功能,Lua模塊提供了相關的API來實現重定向的功能,主要有:
ngx.exec
語法:ngx.exec(uri, args?)
主要實現的是內部的重定向,等價於下面的rewrite指令
rewrite regrex replacement last;
例子:
ngx.exec('/some-location'); ngx.exec('/some-location', 'a=3&b=5&c=6'); ngx.exec('/some-location?a=3&b=5', 'c=6');
注意:
1. 如果給定的uri是命名的location,那么args就會被自動忽略的,如下所示:
location /foo { content_by_lua ' ngx.exec("@bar"); '; } location @bar { ... }
2. args參數可以以string的形式給出,也可以以lua table的形式給出,如下所示:
ngx.exec("/foo","a=3&b=hello%20world") ngx.exec("/foo",{ a= 3, b="hello world"})
3. 該方法不會主動返回,因此,強烈建議在調用該方法時,最好顯示加上return,如下所示:
return ngx.exec(...)
4. 該方法不像ngx.redirect方法,不會產生額外的網絡流量。
ngx.redirect
語法:ngx.redirect(uri, status?)
該方法會給客戶端返回一個301/302重定向,具體是301還是302取決於設定的status值,如果不指定status值,默認是返回302 (ngx.HTTP_MOVED_TEMPORARILY),其等價於下面的rewrite指令:
rewrite ^ /foo? permanent;# nginx config
如果返回301,那么等價於下面的rewrite指令:
rewrite ^ /foo? redirect;# nginx config
要注意與ngx.location.capture*的區別
ngx.location.capture*主要是通過子請求的方式實現location的重新定位的,它與上面的兩種方法完全不同的。
Subrequests are completely different from HTTP 301/302 redirection (viangx.redirect) and internal redirection (viangx.exec).
ngx.req.set_uri
語法: ngx.req.set_uri(uri, jump?)
通過參數uri重寫當前請求的uri;參數jump,表明是否進行locations的重新匹配。當jump為true時,調用ngx.req.set_uri后,nginx將會根據修改后的uri,重新匹配新的locations;如果jump為false,將不會進行locations的重新匹配,而僅僅是修改了當前請求的URI而已。jump的默認值為false。
jump為true,等價於rewrite...last
jump為false,等價於rewrite...break
例如:
ngx.req.set_uri("/foo", true)
等價於
rewrite ^ /foo last;
而
rewrite ^ /foo break;
等價於
ngx.req.set_uri("/foo", false) 或 ngx.req.set_uri("/foo")
轉自:http://blog.csdn.net/weiyuefei/article/details/38434797