How to configure nginx for a RESTful API?

M. Timtow picture M. Timtow · Sep 14, 2017 · Viewed 11.3k times · Source

I have a RESTful web service which exposes an interface such as :

  • GET /api/v1/films/:id/thumb
  • PUT /api/v1/films/:id/thumb
  • ...

The Web Server is composed of a nodejs cluster behind a nginx reverse proxy.

I am now trying to configure nginx proxy and client buffers. To this end I set the directives

    location ~ /api/v1/films/(.*)/thumb {
        proxy_buffers 6 500k;
        proxy_busy_buffers_size 1m;
        client_max_body_size 3m;
        client_body_buffer_size 3m;
        proxy_pass http://backend;
    }

This configuration does the job but is unsatisfying since it configures proxy_buffers 3m for the PUT request which is unnecessary and a waste of resources and a client_max_body_size 3m for a GET.

And so I am looking for a way of configuring my routes based on http methods in addition to URIs.

Thanks to everyone willing to share a bit of experience.

Answer

abeyaz picture abeyaz · Sep 14, 2017

You can map the http method to max body size you want. This should work for example:

map $request_method $max_size {
    default       3m;
    PUT           1m;
    GET           1m;
}

location ~ /api/v1/films/(.*)/thumb {
    proxy_buffers 6 500k;
    proxy_busy_buffers_size 1m;
    client_max_body_size $max_size;
    client_body_buffer_size $max_size;
    proxy_pass http://backend;
}