最近和某行合作,使用某行APP访问我们的web,会post一个user_id的参数,我们需要获取这个user_id做一些验证。前端同事要求把这个post请求转换成get请求才能拿到user_id参数。
刚接到这个需求,一脸懵逼,经过2天各种查资料、实验终于把问题解决。
这里实现的方案是通过nginx+lua 来获得post请求的参数
环境:

centos:6.x  or  7.x

nginx:1.6.3                                     

LuaJIT:2.0.5

lua-nginx-module:0.10.2

ngx_devel_kit:0.3.0

一:准备环境

1,安装LuaJIT

tar xvf LuaJIT-2.0.5.tar.gz
cd LuaJIT-2.0.5
make PREFIX=/usr/local/lj2
make install PREFIX=/usr/local/lj2

2,安装lua-nginx-module

https://github.com/openresty/lua-nginx-module/archive/v0.10.2.tar.gz

tar xvf lua-nginx-module-0.10.2.tar.gz
mv lua-nginx-module-0.10.2 /usr/local/lua-nginx-module

3,安装ngx_devel_kit

https://github.com/simpl/ngx_devel_kit/archive/v0.3.0rc1.tar.gz

tar xvf ngx_devel_kit-0.3.0rc1.tar.gz
mv ngx_devel_kit-0.3.0rc1 /usr/local/ngx_devel_kit

4,安装nginx

tar xvf nginx-1.6.3.tar.gz
cd nginx-1.6.3
export LUAJIT_LIB=/usr/local/lj2/lib
export LUAJIT_INC=/usr/local/li2/include/luajit-2.0
./configure --prefix=/usr/local/nginx --with-http_v2_module --with-ld-opt="-Wl,-rpath,/usr/local/lj2/lib/" --add-module=/usr/local/lua-nginx-module --add-module=/usr/local/ngx_devel_kit
make
make install

二,配置nginx

    server {
        listen       80;
        server_name  www.test.com;
        location /{
                root html;
                index index.html;
                access_log logs/test.log;
                set $user_id '';
                rewrite_by_lua '
                        local request_method = ngx.var.request_method
                        if "GET" == request_method then
                                local arg = ngx.req.get_uri_args()["user_id"] or 0
                                ngx.var.user_id = arg
                        elseif "POST" == request_method then
                                ngx.req.read_body()
                                local arg = ngx.req.get_post_args()["user_id"] or 0
                                ngx.var.user_id = arg
                        end;';
                error_page   405 =200 http://$host$request_uri#/?user_id=$user_id;
        }
    }

到此接触

某行APP  post请求 带参数 user_id   成功转换成 get请求!