nginx-使用lua进行POST参数解析并转发

有这样一个需求:根据请求中的各参数使用nginx转发到本地或者其他主机的不同端口。
首先需要安装lua模块:

安装LuaJIT

wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz
tar -xvf LuaJIT-2.0.2.tar.gz
cd LuaJIT-2.0.2
make instal

安装nginx及部分组件

下载ngx_devel_kit、lua-nginx-module、nginx并解压
wget https://github.com/simpl/ngx_devel_kit/archive/v0.3.0.tar.gz
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.9rc7.tar.gz
wget http://nginx.org/download/nginx-1.14.0.tar.gz 

tar -xvf v0.3.0.tar.gz
tar -xvf v0.10.9rc7.tar.gz
tar -xvf nginx-1.12.1.tar.gz

编译Nginx

cd nginx-1.14.0
./configure --prefix=/usr/local/nginx --add-module=../ngx_devel_kit-0.3.0 --add-module=../lua-nginx-module-0.10.9rc7  --with-http_ssl_module  --with-http_stub_status_module  --with-http_gzip_static_module

安装Nginx

# 有可能权限不够,可以通过su,切换到root用户执行
make && make install

启动nginx

/usr/local/nginx/sbin/nginx

验证LUA是否成功

在/usr/local/nginx/conf/ 安装目录下,修改nginx.conf文件(注意不是解压包所在的文件夹)
在Server中添加如下代码:

# 表示访问/hello 这个url的请求都打印hello,lua
location /hello{
        default_type 'text/plain';
        content_by_lua 'ngx.say("hello,lua")';
}
配置生效,并重启nginx
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload

nginx-使用lua进行POST参数解析并转发_第1张图片

使用lua和nginx解析POTS参数,并实现转发

安装cjson

下载cjson
wget http://www.kyne.com.au/~mark/software/download/lua-cjson-2.1.0.tar.gz
解压并安装
tar -xvf lua-cjson-2.1.0.tar.gz 
make
make出错
# error: lua.h: No such file or directory
# 修改Makefile文件,根据自己安装的情况来

nginx-使用lua进行POST参数解析并转发_第2张图片

开始解析post,使用cjson

创建一个 dispatch.lua 文件,路径可以随意,但是要在nginx.conf文件中指定好

# 我把这个  dispatch.lua  文件放在了 /usr/local/nginx/lua 下,nginx就安装在  /usr/local/nginx  下

local request_method = ngx.var.request_method
local arg=nil
if request_method == "GET" then
         arg = ngx.req.get_uri_args()
elseif request_method == "POST" then
         ngx.req.read_body()
         arg = ngx.req.get_post_args()
end

ngx.req.read_body()
local data = ngx.req.get_body_data()

local cjson = require("cjson")
local json = cjson.decode(data)
--for k,v in pairs(json) do
--    ngx.say("参数输出--")
--    ngx.say(k..":"..v)
--end
local ip = json["ip"]
--ngx.say("获取到的ip:",ip)

if ip ~= nil and ip == '8085' then
--    ngx.say("进入ip=8085")
    ngx.exec('@lua_api_suc')
else
    ngx.exec('@lua_api_err')
end
nginx.config配置
server {
        listen       80;
        server_name  localhost;
        location / {
           proxy_pass http://127.0.0.1:8085;
        }
        location /hello{
        default_type 'text/plain';
        content_by_lua 'ngx.say("hello,lua")';
        }
         location /lua {
             content_by_lua_file "lua/dispatch.lua";
         }
        location @lua_api_suc {
		 content_by_lua_block {
              ngx.say("转发端口8085")
         }
         }
        location @lua_api_err {
         content_by_lua_block {
              ngx.exec("/")
         }
         }

postman传参:
nginx-使用lua进行POST参数解析并转发_第3张图片

可以看到确实成功解析了post中的ip参数,而且做出了想要的动作!

你可能感兴趣的:(nginx-使用lua进行POST参数解析并转发)