index.js (1621B)
1 var http = require('http'), 2 httpProxy = require('http-proxy'); 3 4 var port = process.env.PORT || 3000, 5 proxies = {}, 6 commonRegex = { 7 targetHost: new RegExp('(.*)(localhost|'+(process.env.DOMAIN)+')', 'i'), 8 dotProtocol: /^(https?)\./i, 9 trimDots: /(^\.|\.$)/g, 10 protocol: /^https?:\/\//i 11 }; 12 13 function error_500(res) { 14 res.writeHead(500, { 15 'Content-Type': 'text/plain' 16 }); 17 res.end('Internal server error'); 18 } 19 20 var server = http.createServer(function(req, res) { 21 // HTTP 22 23 // Let's get the target host 24 var targetHost = commonRegex.targetHost.exec(req.headers.host)[1] || null, 25 proto = commonRegex.dotProtocol.test(targetHost); 26 27 // Fix the protocol 28 if (proto) { 29 targetHost = targetHost.replace(commonRegex.dotProtocol, function() { 30 return arguments[1]+'://'; 31 }); 32 } else { 33 targetHost = 'http://' + targetHost; 34 } 35 36 // Strip surrounding dots 37 targetHost = targetHost.replace(commonRegex.trimDots, ''); 38 39 // Check if we have a proxy for this yet 40 if (!proxies[targetHost]) { 41 try { 42 proxies[targetHost] = new httpProxy.createProxyServer({ 43 target:targetHost, 44 autoRewrite: true, 45 cookieDomainRewrite: req.headers.host 46 }); 47 } catch(e) { 48 console.log(e); 49 proxies[targetHost] = null; 50 } 51 } 52 53 // And proxy the request 54 req.headers.host = targetHost.replace(commonRegex.protocol, ''); 55 proxies[targetHost].web(req, res); 56 }); 57 58 server.on('upgrade', function(req, socket, head) { 59 // Websockets 60 }); 61 62 server.listen(port); 63 console.log("Server now listening on port", port);