Created
April 3, 2012 19:00
-
-
Save neiltron/2294719 to your computer and use it in GitHub Desktop.
Node HTTP proxy with url rewriting.
This file contains hidden or 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 util = require('util'), | |
colors = require('colors'), | |
http = require('http'), | |
httpProxy = require('http-proxy'); | |
// | |
// Http Server with proxyRequest Handler and Latency | |
// | |
var proxy = new httpProxy.RoutingProxy(); | |
http.createServer(function (req, res) { | |
var buffer = httpProxy.buffer(req); | |
setTimeout(function() { | |
proxy.proxyRequest(req, res, { | |
port: 9000, | |
host: 'localhost', | |
buffer: buffer | |
}); | |
}, 200); | |
}).listen(8000); | |
// | |
// Target Http Server | |
// | |
http.createServer(function (req, response) { | |
var options = { | |
host: 'newurl.com', | |
port: 80, | |
path: req.url, | |
method: 'GET' | |
}; | |
var req = http.get(options, function(res) { | |
var pageData = ""; | |
res.setEncoding('utf8'); | |
res.on('data', function (chunk) { | |
pageData += chunk; | |
}); | |
res.on('end', function(){ | |
response.write(pageData) | |
response.write("<script type='text/javascript'>var linkRewriter = function(a, b) {$('a[href*=\"' + a + '\"]').each(function() {$(this).attr('href', $(this).attr('href').replace(a, b));});};linkRewriter('newurl.com', 'temp.url.com');</script>") | |
response.end() | |
}); | |
}); | |
}).listen(9000); | |
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8004 '.yellow + 'with proxyRequest handler'.cyan.underline + ' and latency'.magenta); | |
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Slight modification of standalone-proxy.js from the node-http-proxy examples.
I used this for a dev site that was only accessible via modifications to /etc/hosts. The client's network squashed our /etc/hosts entries, so I set this up on our server to proxy the site for demo purposes. ENJOY.
Just replace 'newurl.com' with the url you used in your hosts file, and replace 'temp.url.com' with whatever internet-accessible url you are using.