Nginx Change Request from PUT to POST

nginx, rest

Solution

Nginx only informs FastCGI of the request method via `REQUEST_METHOD` param. So you may simply override the value and report anything you want to PHP. You'll have to declare another variable in your Nginx configuration, let's name it `$fcgi_method`, based on the original request method:

map $request_method $fcgi_method {
  default $request_method;
  PUT POST;
}

(note that `map` sections should be at `http` level, i.e. the same configuration level as `server` blocks)

Then you may use it in your location like so:

fastcgi_param REQUEST_METHOD  $fcgi_method;

It's important that this snippet is after typical `include fastcgi_params` or alike.

Problem

I'm using nginx for a PHP REST API that I'm working on. To be fully REST-ful, I'm using `PUT`/`DELETE` requests where appropriate. However, PHP doesn't parse the post body on `PUT` requests - which I need for this particular scenario. I had considered parsing it myself, but a) I'd rather let PHP do it in C as it's considerably faster than any implementation I could come up with in PHP and b) there are a lot of edge cases that people have already spent a lot of time working around - I'd rather not duplicate those efforts. On the API side, I have already added support to read the `X-HTTP-Method-Override` header and use that when available over the actual verb. All I'm looking for now is a way, in nginx, to take a `PUT` request, and change it to a `POST` request with that header set. I feel ike I have looked all over the place but can't find a solution. Anything would be helpful (even if you recommend a different parsing technique so I don't have to deal with this).

Original source