Nginx-Lua重定向系列
Ningx Lua 模塊官方文檔
Nginx Lua 模塊原理和函數(shù)
在Nginx中實(shí)現(xiàn)重定向可以通過rewrite指令,具體可參考《Nginx學(xué)習(xí)——http_rewrite_module的rewrite指令》
通過Lua模塊也可以實(shí)現(xiàn)同樣的功能,Lua模塊提供了相關(guān)的API來實(shí)現(xiàn)重定向的功能,主要有:
ngx.exec語法:ngx.exec(uri, args?)
主要實(shí)現(xiàn)的是內(nèi)部的重定向,等價于下面的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參數(shù)可以以string的形式給出,也可以以lua table的形式給出,如下所示:
ngx.exec("/foo", "a=3&b=hello%20world")
ngx.exec("/foo", { a=3, b="hello world"})
? ? ? ?3.該方法不會主動返回,因此,強(qiáng)烈建議在調(diào)用該方法時,最好顯示加上return,如下所示:
? ?return ngx.exec(...)
? ? ? ?4.該方法不像ngx.redirect方法,不會產(chǎn)生額外的網(wǎng)絡(luò)流量。
ngx.redirect
? ? 語法:ngx.redirect(uri, status?)
? ? 該方法會給客戶端返回一個301/302重定向,具體是301還是302取決于設(shè)定的status值,如果不指定status值,默認(rèn)是返回302
? ? (ngx.HTTP_MOVED_TEMPORARILY),其等價于下面的rewrite指令:
? ? rewrite ^ /foo? permanent;# nginx config
? ? 如果返回301,那么等價于下面的rewrite指令:
rewrite ^ /foo? redirect;# nginx config? ? ?要注意與ngx.location.capture*的區(qū)別
? ? ?ngx.location.capture*主要是通過子請求的方式實(shí)現(xiàn)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?)
通過參數(shù)uri重寫當(dāng)前請求的uri;參數(shù)jump,表明是否進(jìn)行l(wèi)ocations的重新匹配。當(dāng)jump為true時,調(diào)用ngx.req.set_uri后,nginx將會根據(jù)修改后的uri,重新匹配新的locations;如果jump為false,將不會進(jìn)行l(wèi)ocations的重新匹配,而僅僅是修改了當(dāng)前請求的URI而已。jump的默認(rèn)值為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")
轉(zhuǎn)自:http://blog.csdn.net/weiyuefei/article/details/38434797
總結(jié)
以上是生活随笔為你收集整理的Nginx-Lua重定向系列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: curl的使用
- 下一篇: Nginx学习笔记---ngx_tabl