Last Updated: February 25, 2016
·
1.088K
· sean9999

node.js proxy server, useful for vagrant and local dev

Sometimes when I'm developing a site locally that makes use of subdomains and/or alternate domains, i want links to resources in the markup to resolve properly. This little node.js proxy server listens for certain hosts on port 80, and forwards those requests to a port that vagrant is listening on. This is one way to skin a cat: My way.

It is meant to be run on your host machine, when vagrant is listening on port 8080, and you have the desired hosts listed in /etc/hosts on both host and guest machines.

var http = require('http');

var server = http.createServer(function(req,res){
    console.log(req.headers.host + req.url);
    var config = {
        "path": req.url,
        "port": 8080,
        "method": req.method,
        "host": req.headers.host,
        "agent": false
    };
    config.headers = req.headers;
    var req2 = http.request(config,function(res2){
        res.statusCode = res2.statusCode;
        //  depending on your use case, you may wish to omit certain headers
        var omit_headers = ['x-content-length','x-date','x-etag','x-last-modified'];
        for (var k in res2.headers) {
            if ( omit_headers.indexOf(k) === -1 ) {
                res.setHeader(k,res2.headers[k]);
            }
        }
        res2.on('data',function(chunk){
            res.write(chunk);
        });
        res2.on('end',function(){
            res.end();
        });
    });
    req2.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });
    req2.end();
});

['mydomain.dev','z.mydomain.dev'].forEach(function(thishost){
    server.listen(80,thishost,function(){
        console.log('listening for ' + thishost + ' on :80');
    });
});