Using Node.js to redirect and proxy normal HTTP+WebSocket traffics based on hostnames
/ 2 min read
Usually I used to use a single server to host several developing or experimental projects. Thus I need a quick solution to forward different request to these services. I had tried to use nginx before. But now I have a easier way to do so.
-
require modules
-
var http = require('http'),_ = require('underscore'),httpProxy = require('http-proxy');
-
config proxy(forward) and redirect mappings (hostname based)
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/'}; -
Create an instance of node-http-proxy’s RoutingProxy
var proxy = new httpProxy.RoutingProxy(proxyOptions); -
Proxy normal HTTP requests
var server = http.createServer(function(req, res) {var oriHost = req.headers.host,//remove port number from original hosthost = oriHost.indexOf(":") ? oriHost.split(':')[0] : oriHost;//Check matches of redirect hostnamesif(_.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 requestsproxy.proxyRequest(req, res);}}); -
Proxy websocket requests and listen the main service on specific port
server.on('upgrade', function(req, socket, head) {proxy.proxyWebSocketRequest(req, socket, head);});server.listen(80);
Its very convenient and then I can use a simple forever service to manage this service.
-
Download original JavaScript file on here - Gist
-
Ref: