本节主要是带着大家简单的过一下常用的ngx_lua API。
一、nginx lua directives和api
ngx_lua 有60多个指令(Directive),140多个 API(截止到2019-3-26)。
官方lua文档:
https://www.nginx.com/resources/wiki/modules/lua/
https://github.com/openresty/lua-nginx-module
1、指令 是 ngx_lua 提供给Nginx调用的方法,与 Nginx自带的 location
、rewrite
等是一个级别的。指令有自己的作用域,例如:content_by_lua_file
只能作用于location
和location if
里面:
2、API 是指ngx_lua基于lua代码实现的一系列方法或常量,遵循 lua的语法规则。只能在lua代码块或者lua文件里使用。
例如:
content_by_lua '
ngx.say("<p>hello, world</p>")
';
其中content_by_lua
是指令,作用于location
块;ngx.say()
是 ngx_lua 提供的API。
在官方文档上可以找到指令及API所在的位置:
下面,我们使用 ngx_lua完成另外一个小功能:实现base64的解码并重新json编码输出。代码里会用到一些指令和API。
二、测试ngx lua API
lua代码:
nginx/conf/lua/decode_info.lua
-- 实现base64的解码并重新json编码输出
local json = require "cjson"
ngx.req.read_body()
local args = ngx.req.get_post_args()
if not args or not args.info then
ngx.exit(ngx.HTTP_BAD_REQUEST)
end
local client_ip = ngx.var.remote_var or '127.0.0.1'
local user_agnet = ngx.req.get_headers()['user_agent'] or ''
local info = ngx.decode_base64(args.info)
local res = {}
res.client_ip = client_ip
res.user_agnet = user_agnet
res.info = info
ngx.say(json.encode(res))
修改 nginx.conf ,新增:
location /decode_info {
content_by_lua_file conf/lua/decode_info.lua;
}
$php -r "echo base64_encode('test');"
dGVzdA==
$ curl -XPOST -d "info=dGVzdA==" http://127.0.0.1:8080/decode_info
{"user_agnet":"curl\/7.19.7","client_ip":"127.0.0.1","info":"test"}
说明:
1、require
是 lua 里面引入其他库的关键字。这里引入的 cjson。
2、当我们要读取 http里的post数据的时候,就需要使用ngx.req.read_body()
。该API同步读取客户端请求主体而不阻塞Nginx事件循环。
3、ngx.req.get_post_args()
用于获取post请求数据。
4、ngx.var.remote_var
实际是获取的nginx里的变量remote_var
。也就是说,ngx.var.xxx
实际是获取的nginx里的变量xxx
。例如
nginx变量详见:[Alphabetical index of variables}(http://nginx.org/en/docs/varindex.html)。 ngx_lua ngx.var
API详见:ngx.var.VARIABLE。
5、ngx.req.get_headers()
用于读取nginx的header参数。返回的是lua table。
6、ngx.decode_base64()
用于 base64字符串解码。对应的编码API是 ngx.encode_base64()
。