使用 nginx 将请求从 POST 重写为 GET

Sta*_*asM 5 rewrite http nginx

我有一个后端服务器,由于各种原因,它只处理 GET 请求。该服务器位于 nginx 代理后面(即所有访问都对 nginx 进行,nginx 通过 代理将其发送到后端proxy_pass)。是否可以使 nginx 将 POST 请求重写为 GET 请求,即POST /foo主体内容类型application/x-www-form-urlencoded和主体foo=bar将被代理GET /foo?foo=bar

Fal*_*ius 5

这个小例子在 ubuntu 16.04 上使用 nginx 1.10.x 和 nginx-extras (包含 lua)为我工作。它不尊重请求中的查询参数,将它们与帖子正文合并。

server {
    ...
    server_name ...;

    client_max_body_size 4k; # prevent too long post bodies

    location / {
            if ($request_method = POST ) {
                access_by_lua '
                        ngx.req.read_body()
                        local data = ngx.req.get_body_data()
                        ngx.req.set_uri_args(data)
                ';                
            }

            proxy_pass http://yourupstreamdestination;
            proxy_method GET;                    # change method
            include /etc/nginx/proxy_params.inc; # include some params
    }
}
Run Code Online (Sandbox Code Playgroud)