Nginx-Lua重定向系列
Ningx Lua 模塊官方文檔
Nginx Lua 模塊原理和函數
在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
總結
以上是生活随笔為你收集整理的Nginx-Lua重定向系列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: curl的使用
- 下一篇: Python基于python实现的htt