Nginx proxy_set_header base on verb

nginx

I have a buggy client which sends a bad Content-Type header when POSTing to a specific url. The API in question already sits behind an nginx 1.15 reverse proxy, so as a workaround until those clients can be patched, I'd like to just rewrite the Content-Type header for those requests. I naively tried to set it up like this:

location /api/file {
    if ($request_method = POST ) {
      proxy_set_header Content-Type "application/octet-stream";
    }
    proxy_pass http://<api server>/api/file;
}

But I get this error:

"proxy_set_header" directive is not allowed here

The same /api/file endpoint also supports GET and HEAD methods, which I'd prefer to leave alone. How can I configure this to only apply the proxy_set_header to POST requests?

Update

For now I've just removed the if block entirely and blanket applied the header. Sending Content-Type on a GET or HEAD makes no sense, but my API server ignores it in those cases, and this is already a hack anyway.

Best Answer

I would use map directive.

map $request_method $content_type_header {
  default $http_content_type;
  "POST"  "application/octet_stream";
}

server {
  ...
  location /api/file {
    proxy_pass http://server/api/file;
    proxy_set_header Content-Type $content_type_header;
  }
}