Nginx Lua - rewrite url, forward original POST data/multipart form data

1.6k Views Asked by At

Nginx with its Lua extension makes it very easy to examine and manipulate a request prior to having it dispatched as appropriate. In my current project I am trapping all requests that arrive at a specified folder location, examining the request and then having it executed by an entirely different script. An outline of what I do:

/etc/nginx/sites-available/default Configuration

location /myfolder{
 rewrite_by_lua_file "/path/to/rewrite.lua";
 lua_need_request_body "on";
}

In rewrite.lua

ngx.req.set_header('special','my_special-header');  
local data = ngx.req.get_body_data();
ngx.req.set_body_data(data);

and finally redirecting to another location:

ngx.req.set_uri("/myother/index.php",true);

With simple GET requests or POST requests with one or two items of attached POST data this works well. The issue I have been unable to resolve is this. Say for instance I am sending out multipart from data in my original request.

ngx.req.get_body_data()

actually gets the raw request body. If I forward this to /myother/index.php I can retrieve this as file_get_contents('php://input'). This is OK but not good enough. I don't want to have to deal with the raw input here. I would rather be able to work with standard PHP $_POST and $_FILES variables. However, those are empty and the their contents are present in the body as a text string.

Is there a way to tell Nginx that when I subject a user request to some treatment by Lua prior to forwarding it to another URL, it should just pass on the POST/PUT request fields as well as the whole of the original $_FILES array?

0

There are 0 best solutions below