Skip to content

Instantly share code, notes, and snippets.

@ryanhanwu
Created July 18, 2013 17:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanhanwu/6031480 to your computer and use it in GitHub Desktop.
Save ryanhanwu/6031480 to your computer and use it in GitHub Desktop.
Node.js HTTP hostname redirect and proxy normal HTTP+WebSockets traffic
var http = require('http'),
_ = require('underscore'),
httpProxy = require('http-proxy');
var proxyOptions = {
router: {
"api.testAppX.com" : 'localhost:2041',
"dev.api.testAppX.com" : 'localhost:2042',
"www.testAppY.com" : 'localhost:10520',
"test.oldApps.com" : 'localhost:10520',
'bc.ryanwu.co' : 'localhost:8888'
}
},
redirectOptions = {
'olddomain.com' : 'http://newdomain.com/',
'www.olddomain.com' : 'http://newdomain.com/',
'blog.olddomain.com' : 'http://newdomain.com/blog/'
};
var proxy = new httpProxy.RoutingProxy(proxyOptions);
var server = http.createServer(function(req, res) {
var oriHost = req.headers.host,
//remove port number from original host
host = oriHost.indexOf(":") ? oriHost.split(':')[0] : oriHost;
//Check matches of redirect hostnames
if(_.has(redirectOptions, host)) {
res.writeHead(301, { //You can use 301, 302 or whatever status code
'Location': redirectOptions[host],
'Expires': (new Date()).toGMTString()
});
res.end();
} else {
//Routing proxy will handle the rest of requests
proxy.proxyRequest(req, res);
}
});
server.on('upgrade', function(req, socket, head) {
proxy.proxyWebSocketRequest(req, socket, head);
});
server.listen(80);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment