Node.js HTTP hostname redirect and proxy normal HTTP+WebSockets traffic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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