Thursday, September 8, 2011

NGINX Proxy solves CORS dilema

Hi guys,

This is a really special announcement:

We worked around our CORS IE problem, by adding some simple NGINX proxy's.

The problem we had was that CORS in IE doesn't support the with credentials directive, which is required for using sessions. (See fancy explanation here: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/)

First we use $.support.cors from jQuery, which confirms that they have credentials support./

If they don't support it we modify their URLs to have the base server name in the path. (In our case links to something.i.tv would result in i.tv/something/)

Then in our NGINX conf, we used proxy_pass to send people that go to those URLs to the real server:
http://wiki.nginx.org/HttpProxyModule#proxy_pass

Here is the code:
location /something/ {
    proxy_pass http://something.i.tv/;
}

We had previously looked at node-httpd-proxy, building our own proxy server, trying a million hacks to get CORS to work with IE, wrapping everything in JSONP (doesn't work well with long POSTs), but this ended up working the best (and it's by far the easiest)!

Go Node.js, Express and NGINX! We love these things at i.tv.