How to make Socket.IO work behind nginx (mostly)
UPDATE: News from jpetazzo:
dotCloud now has beta websockets support, so this hack should no longer be necessary. Just point your custom domain to experimental-gateway-1.dotcloud.com instead of gateway.dotcloud.com and you will be using a websockets-aware load balancer instead of the default one running Nginx.
Most web hosts with node.js support host it behind an nginx proxy. Sadly, Socket.IO doesn’t work at all behind nginx without a bit of hacking. Currently there’s no vhost-supported way to run websockets through nginx, but we can at least get the xhr transport to work properly–basically everything can do xhr-polling.
Turns out that nginx doesn’t really like how Socket.IO uses the “Connection: keep-alive” header, so lets just remove that. All we need to do is overwrite a function in the xhr-polling transport. This should do it;
io.configure(function() {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
var path = require('path');
var HTTPPolling = require(path.join(
path.dirname(require.resolve('socket.io')),'lib', 'transports','http-polling')
);
var XHRPolling = require(path.join(
path.dirname(require.resolve('socket.io')),'lib','transports','xhr-polling')
);
XHRPolling.prototype.doWrite = function(data) {
HTTPPolling.prototype.doWrite.call(this);
var headers = {
'Content-Type': 'text/plain; charset=UTF-8',
'Content-Length': (data && Buffer.byteLength(data)) || 0
};
if (this.req.headers.origin) {
headers['Access-Control-Allow-Origin'] = '*';
if (this.req.headers.cookie) {
headers['Access-Control-Allow-Credentials'] = 'true';
}
}
this.response.writeHead(200, headers);
this.response.write(data);
this.log.debug(this.name + ' writing', data);
};
});
-
http://twitter.com/jyoungblood jonathan youngblood
-
http://srirangan.net Srirangan
-
http://www.stephenbelanger.com Stephen Belanger
-
http://srirangan.net Srirangan
-
http://www.stephenbelanger.com Stephen Belanger
-
http://twitter.com/hosamebrahim hosam.ebrahim
-
http://www.stephenbelanger.com Stephen Belanger