企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Nginx Lua API 和一般的Web Server类似,我们需要接收请求、处理并输出响应。而对于请求我们需要获取如请求参数、请求头、Body体等信息;而对于处理就是调用相应的Lua代码即可;输出响应需要进行响应状态码、响应头和响应内容体的输出。因此我们从如上几个点出发即可。 ## 接收请求 #### 1. openResty.conf配置文件 ``` server { listen 80; server_name _; location ~ /lua_request/(\d+)/(\d+) { # 设置nginx变量 set $a $1; set $b $host; default_type 'text/html'; lua_code_cache off; # nginx内容处理 # content_by_lua_file /usr/openResty/lua/test.lua; content_by_lua_file /usr/example/lua/test_request.lua; # 内容体处理完成后调用 echo_after_body "ngx.var.b $b"; } } ``` #### 2. test_request.lua ``` -- nginx变量 local var = ngx.var ngx.say("ngx.var.a : ", var.a, "<br/>") ngx.say("ngx.var.b : ", var.b, "<br/>") ngx.say("ngx.var[2] : ", var[2], "<br/>") ngx.var.b = 2; ngx.say("<br/>") -- 请求头 local headers = ngx.req.get_headers() ngx.say("headers begin", "<br/>") ngx.say("Host : ", headers["Host"], "<br/>") ngx.say("user-agent : ", headers["user-agent"], "<br/>") ngx.say("user-agent : ", headers.user_agent, "<br/>") for k, v in pairs(headers) do if type(v) == "table" then ngx.say(k, ":", table.concat(v, ","), "<br/>") else ngx.say(k, " : ", v, "<br/>") end end ngx.say("headers end", "<br/>") ngx.say("<br/>") -- get请求uri参数 ngx.say("uri args begin", "<br/>") local uri_args = ngx.req.get_uri_args() for k, v in pairs(uri_args) do if type(v) == "table" then ngx.say(k, " : ", table.concat(v, ", "), "<br/>") else ngx.say(k, ": ", v, "<br/>") end end ngx.say("uri args end", "<br/>") ngx.say("<br/>") -- post请求参数 ngx.req.read_body() ngx.say("post args begin", "<br/>") local post_args = ngx.req.get_post_args() for k, v in pairs(post_args) do if type(v) == "table" then ngx.say(k, ":", table.concat(v, ", "), "<br/>") else ngx.say(k, ": ", v, "<br/>") end end ngx.say("post args end", "<br/>") ngx.say("<br/>") -- 请求的http协议版本 ngx.say("ngx.req.http_version:", ngx.req.http_version(), "<br/>") -- 请求方法 ngx.say("ngx.req.get_method:", ngx.req.get_method(), "<br/>") -- 原始的请求头内容 ngx.say("ngx.req.raw_header:", ngx.req.raw_header(), "<br/>") -- 请求的body内容体 ngx.say("ngx.req.get_body_data():", ngx.req.get_body_data(), "<br/>") ngx.say("<br/>") ``` **ngx.var** : nginx变量,如果要赋值如ngx.var.b = 2,此变量必须提前声明;另外对于nginx location中使用正则捕获的捕获组可以使用ngx.var\[捕获组数字\]获取; **ngx.req.get\_headers**:获取请求头,默认只获取前100,如果想要获取所以可以调用ngx.req.get\_headers(0);获取带中划线的请求头时请使用如headers.user\_agent这种方式;如果一个请求头有多个值,则返回的是table; **ngx.req.get\_uri\_args**:获取url请求参数,其用法和get\_headers类似; **ngx.req.get\_post\_args**:获取post请求内容体,其用法和get\_headers类似,但是必须提前调用**ngx.req.read\_body()**:来读取body体(也可以选择在nginx配置文件使用lua\_need\_request\_body on;开启读取body体,但是官方不推荐); **ngx.req.raw\_header**:未解析的请求头字符串; **ngx.req.get\_body\_data**:为解析的请求body体内容字符串。 <br/> 如上方法处理一般的请求基本够用了。另外在读取post内容体时根据实际情况设置[client\_body\_buffer\_size](http://wiki.nginx.org/HttpCoreModule#client_body_buffer_size "HttpCoreModule")和[client\_max\_body\_size](http://wiki.nginx.org/HttpCoreModule#client_max_body_size "HttpCoreModule")来保证内容在内存而不是在文件中。 <br/> 使用如下脚本测试 ``` wget --post-data 'a=1&b=2' 'http://127.0.0.1/lua_request/1/2?a=3&b=4' -O - ``` 结果如下所示: ![](https://box.kancloud.cn/37760d21fc120b3a1b5372fdfddc65f3_1698x856.png) ## 输出响应 #### 1. openResty.conf配置文件增加配置 ``` location /lua_response_1 { default_type "text/html"; content_by_lua_file /usr/openResty/lua/test_response_1.lua; } ``` #### 2. test_response_1.lua ``` -- 写响应头 ngx.header.a = "1" -- 多个响应头可用table ngx.header.b = {"2", "3"} -- 输出响应 ngx.say("a", "b", "<br/>") ngx.print("c", "d", "<br/>") -- 200状态码退出 return ngx.exit(200) ``` **ngx.header**:输出响应头; **ngx.print**:输出响应内容体; **ngx.say**:通ngx.print,但是会最后输出一个换行符; **ngx.exit**:指定状态码退出。 使用postman测试结果如下 ![](https://box.kancloud.cn/05f51d7d6a32031f9a8ac12bfaec1c11_598x468.png) ![](https://box.kancloud.cn/ad723cde217fc7270b79728e7cf74aed_602x484.png) ## 重定向 #### 1. openResty.conf配置文件增加配置 ``` location /lua_response_2 { default_type "text/html"; content_by_lua_file /usr/openResty/lua/test_response_2.lua; } ``` #### 2. test_response_2.lua ``` ngx.redirect("https://www.baidu.com", 302) ``` **ngx.redirect**:重定向 **ngx.status**:状态码,设置响应的状态码 **ngx.resp.get_headers()**:获取设置的响应状态码 **ngx.send_headers()**:发送响应状态码,当调用ngx.say/ngx.print时自动发送响应状态码;可以通过 **ngx.headers_sent=true**:判断是否发送了响应状态码 ## 其他API #### 1. openResty.conf配置文件增加配置 ``` location /lua_other { default_type "text/html"; content_by_lua_file /usr/openResty/lua/test_other.lua; } ``` #### 2. test_other.lua ``` -- 未经解码的请求uri local request_uri = ngx.var.request_uri; ngx.say("request_uri : ", request_uri, "<br/>"); -- 解码 ngx.say("decode request_uri : ", ngx.unescape_uri(request_uri), "<br/>"); -- MD5 ngx.say("ngx.md5 : ", ngx.md5("123"), "<br/>"); -- http time ngx.say("ngx.http_time : ", ngx.http_time(ngx.time()), "<br/>"); ``` **ngx.escape_uri/ngx.unescape_uri** : uri编码解码; **ngx.encode_args/ngx.decode_args**:参数编码解码; **ngx.encode_base64/ngx.decode_base64**:BASE64编码解码; **ngx.re.match**:nginx正则表达式匹配; 更多Nginx Lua API请参考 [http://wiki.nginx.org/HttpLuaModule#Nginx_API_for_Lua](http://wiki.nginx.org/HttpLuaModule#Nginx_API_for_Lua) ## Nginx全局内存 使用过如Java的朋友可能知道如Ehcache等这种进程内本地缓存,Nginx是一个Master进程多个Worker进程的工作方式,因此我们可能需要在多个Worker进程中共享数据,那么此时就可以使用[ngx.shared.DICT](http://wiki.nginx.org/HttpLuaModule#ngx.shared.DICT.incr)来实现全局内存共享。 #### 1. 首先在nginx.conf的http部分分配内存大小 ``` #共享全局变量,在所有worker间共享 lua_shared_dict shared_data 1m; ``` #### 2. openResty.conf配置文件增加配置 ``` location /lua_shared_dict { default_type "text/html"; content_by_lua_file /usr/openResty/lua/test_lua_shared_dict.lua; } ``` #### 3. test_lua_shared_dict.lua ``` -- 1. 获取全局共享内存变量 local shared_data = ngx.shared.shared_data -- 2. 获取字典值 local i = shared_data:get("i") if not i then i = 1 -- 3. 惰性赋值 shared_data:set("i", i) ngx.say("lazy set i ", i, "<br/>") end -- 递增 i = shared_data:incr("i", i) ngx.say("i=", i, "<br/>") ``` 更多API请参考[http://wiki.nginx.org/HttpLuaModule#ngx.shared.DICT](http://wiki.nginx.org/HttpLuaModule#ngx.shared.DICT) 到此基本的Nginx Lua API就介绍完了,对于请求处理和输出响应如上介绍的API完全够用了,更多API请参考官方文档。