Is it possible to route requests to different applications via Content-Type?

I'm designing a JSON API, and I'd like to version the API using content negotiation of some kind. I'm currently planning on using Vendor MIME Types to do this.

While I can definitely do this at the application level, I'm thinking it would be best to make this happen at the HTTP server level. Is this possible with Apache or nginx?

The Content-Type would look something like: application/vnd.vendorname-v1+json or possibly using parameters: application/vnd.vendorname+json;v=1


Solution 1:

Nginx's idiomatic approach to this kind of problems is via map. Please see my answer at StackOverflow.

Basically, you define a map in http section

map $any_variable $my_upstream {
  # Default value:
  default upstream1;

  # Exact match:
  application/vnd.vendorname+json;v=1 upstream2;

  # Regexp:
  ~^application.*vnd.vendorname-v1\+json upstream3;
}

You may mix exact matches and regexps in one map.

Then you simply use $my_upstream in you server or location section(s):

location / {
  proxy_pass http://$my_upstream$uri;
}

Nginx evaluates map variables lazily, only once (per request) and when you are using them.

Solution 2:

Sure; Apache's mod_rewrite could do this with a little bit of RewriteCond, though I'm a bit too rusty to give you an example off the top of my head. In nginx, though, it'd look something like the following (assuming you had two upstreams defined; one for your jsonapp and the other for... otherstuff):

if ($content_type = application/vnd.vendorname-v1+json) {
    proxy_pass http://jsonapp/
    break;
}
proxy_pass http://otherstuff/