◆ 获取uri参数: 1.获取get请求参数:ngx.req.get_uri_args 2.获取post请求参数ngx.req.get_post_args
location /print_param { content_by_lua_block { local arg = ngx.req.get_uri_args() for k,v in pairs(arg) do ngx.say("[GET ] key:", k, " v:", v) end ngx.req.read_body() -- 解析 body 参数之前一定要先读取 body local arg = ngx.req.get_post_args() for k,v in pairs(arg) do ngx.say("[POST] key:", k, " v:", v) end } } ➜ ~ curl '127.0.0.1/print_param?a=1&b=2%26' -d 'c=3&d=4%26' [GET ] key:b v:2& [GET ] key:a v:1 [POST] key:d v:4& [POST] key:c v:3◆ 传递请求 uri 参数: URI内容传递过程中是需要调用 ngx.encode_args 进行规则转义。
location /test { content_by_lua_block { local res = ngx.location.capture( '/print_param', { method = ngx.HTTP_POST, args = ngx.encode_args({a = 1, b = '2&'}), body = ngx.encode_args({c = 3, d = '4&'}) } ) ngx.say(res.body) } }输出结果:
➜ ~ curl '127.0.0.1/test' [GET] key:b v:2& [GET] key:a v:1 [POST] key:d v:4& [POST] key:c v:3◆ 获取请求body内容 需先设置lua_need_request_body on,然后再用ngx.req.get_body_data()获取body数据
http { server { listen 80; # 默认读取 body lua_need_request_body on; location /test { content_by_lua_block { local data = ngx.req.get_body_data() ngx.say("hello ", data) } } } } 再次测试,符合我们预期: ➜ ~ curl 127.0.0.1/test -d jack hello jack