使用nginx读取POST变量的表单数据。

我有一个客户端程序,无法修改。它通过WAN链路发送大量包含数百个变量的POST(x-www-form-urlencoded)请求,但我只需要其中的5个。我在本地客户端系统上插入nginx作为反向代理。最简单的方法是让nginx去掉额外的数据是什么?

我目前看到两种方法:

  1. 使用Lua(如果我使用Lua,应该使用content_by_lua,rewrite body,然后进行子请求吗?还是有更简单的方法?)
  2. 使用form-input-nginx-module和proxy_set_body进行解析并获取一些变量。

由于我已经在使用OpenResty,所以Lua不需要额外的模块。但是,这可能意味着编写更多位置等以进行子请求。

点赞
用户1058509
用户1058509

在我看来,最简单的方法是使用 Lua。选择 content_by_lua、rewrite_by_lua、access_by_lua 或它们的任何组合将取决于您如何使用子请求的响应正文。这个决定也将确定是否需要额外的位置。

以下是几个示例:

1. 使用 content_by_lua 对本地位置进行定位。

(此方法需要定义子请求位置)

location /original/url {
    lua_need_request_body on;
    content_by_lua '
        --许多参数,但我只需要子请求的5个参数
        local limited_post_args, err = ngx.req.get_post_args(5)
        if not limited_post_args then
            ngx.say("failed to get post args: ", err)
            return
        end
        local subreq_uri = "/test/local"
        local subreq_response = ngx.location.capture(subreq_uri, {method=ngx.HTTP_POST,
                                body = ngx.encode_args(limited_post_args)})
        ngx.print(subreq_response.body)
    ';
}

location ~/test/local {
    lua_need_request_body on;
    proxy_set_header Accept-Encoding "";
    proxy_pass http://echo.200please.com;
}

2. 使用 rewrite_by_lua 定位到远程目标 (不需要额外的位置)

location /original/url/to/remote {
    lua_need_request_body on;
    rewrite_by_lua '
        --许多参数,但我只需要子请求的5个参数
        local limited_post_args, err = ngx.req.get_post_args(5)
        if not limited_post_args then
            ngx.say("failed to get post args: ", err)
            return
        end

        --设置有限数量的参数
        ngx.req.set_body_data(ngx.encode_args(limited_post_args))
        --重写url
        local subreq_path = "/test"
        ngx.req.set_uri(subreq_path)
    ';
    proxy_pass http://echo.200please.com;
}

带有7个参数的示例 post 请求限制为5个:

curl 'http://localhost/original/url/to/remote' --data 'param1=test&param2=2&param3=3&param4=4&param5=5&param6=6&param7=7' --compressed

响应:

POST /test HTTP/1.0
Host: echo.200please.com
Connection: close
Content-Length: 47
User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Accept: */*
Accept-Encoding: deflate, gzip
Content-Type: application/x-www-form-urlencoded

param3=3&param4=4&param1=test&param2=2&param5=5
2014-11-15 05:57:55