Skip to content

Instantly share code, notes, and snippets.

@neiltron
Created April 3, 2012 19:00
Show Gist options
  • Save neiltron/2294719 to your computer and use it in GitHub Desktop.
Save neiltron/2294719 to your computer and use it in GitHub Desktop.
Node HTTP proxy with url rewriting.
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);
@neiltron
Copy link
Author

neiltron commented Apr 3, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment