lua_code_cache
文法:lua_code_cache on | off
預設: on
適用上下文:http、server、location、location if
這個指令是指定是否開啟lua的代碼編譯緩衝,開發時可以設定為off,以便lua檔案即時生效,如果是生產線上,為了效能,建議開啟。
lua_package_path
文法:lua_package_path
預設:由lua的環境變數決定
適用上下文:http
設定lua代碼的尋找目錄。
例如:lua_package_path "/opt/nginx/conf/www/?.lua;;";
具體的路徑設定要參考lua的模組機制
init_by_lua(_file)
文法:init_by_lua
適用上下文:http
init_by_lua 'cjson = require "cjson"'; server{location= /api {content_by_lua ' ngx.say(cjson.encode({dog = 5, cat = 6})) ';}}
從這段配置代碼,我們可以看出,其實這個指令就是初始化一些lua的全域變數,以便後續的代碼使用。
註:有(_file)的選項代表可以直接引用外部的lua原始碼檔案,效果與直接寫設定檔一樣,不過可維護性當然是分開好點。
init_worker_by_lua(_file)
類似於上面的,不過是作用在work進程的,先於work進程啟動而調用。
set_by_lua(_file)
文法:set_by_lua $res
適用上下文:server、location、location if
location /foo {set$diff'';# we have to predefine the $diff variable here set_by_lua $sum' local a = 32 local b = 56 ngx.var.diff = a - b; -- write to $diff directly return a + b; -- return the $sum value normally ';echo "sum = $sum, diff = $diff";}
這個指令是為了能夠讓nginx的變數與lua的變數相互作用賦值。
content_by_lua(_file)
文法:content_by_lua
適用上下文:location、location if
location /nginx_var {# MIME type determined by default_type:default_type'text/plain'; # try access /nginx_var?a=hello,worldcontent_by_lua "ngx.print(ngx.var['arg_a'], '\\n')";}
通過這個指令,可以由lua直接確定nginx響應頁面的本文。
rewrite_by_lua(_file)
文法:rewrite_by_lua
適用上下文:location、location if
這個指令更多的是為了替代HttpRewriteModule的rewrite指令來使用的,優先順序低於rewrite指令
比如
location /foo { set$a12;# create and initialize $a set$b'';# create and initialize $b rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1'; if($b='13'){ rewrite ^ /bar redirect; break; } echo "res = $b"; }
這個並不會像預期的那樣子,因為我猜測,rewrite_by_lua是開啟一個協程去工作的,可是下面卻繼續執行下去了,所以得不到預期的結果。
此時如果由lua代碼來控制rewrite,那就沒有問題了。
location /foo {set$a12;# create and initialize $aset$b'';# create and initialize $brewrite_by_lua ' ngx.var.b = tonumber(ngx.var.a) + 1 if tonumber(ngx.var.b) == 13 then return ngx.redirect("/bar"); end '; echo "res = $b";}
access_by_lua(_lua)
文法:access_by_lua
適用上下文:http, server, location, location if
location / {deny 192.168.1.1;allow 192.168.1.0/24;allow 10.1.1.0/16;deny all; access_by_lua ' local res = ngx.location.capture("/mysql", { ... }) ... '; # proxy_pass/fastcgi_pass/...}
顧名思義,這個指令用在驗證通過或者需要驗證的時候。
header_filter_by_lua(_file)
文法:header_filter_by_lua
適用上下文:http, server, location, location if
location / {proxy_passhttp://mybackend;header_filter_by_lua 'ngx.header.Foo = "blah"';}
用lua的代碼去指定http響應的 header一些內容。
body_filter_by_lua(_file)
文法:body_filter_by_lua
適用上下文:http, server, location, location if
location /t {echo hello world;echo hiya globe; body_filter_by_lua ' local chunk = ngx.arg[1] if string.match(chunk, "hello") then ngx.arg[2] = true -- new eof return end -- just throw away any remaining chunk data ngx.arg[1] = nil ';}
這個指令可以用來篡改http的響應本文的。
以上就介紹了nginx lua模組常用的指令,包括了方面的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!