Search code examples
node.jsnode-http-proxy

Default route using node-http-proxy?


I want to do a simple node.js reverse proxy to host multiple Node.JS applications along with my apache server on the same port 80. So I found this example here

var http = require('http')
, httpProxy = require('http-proxy');

httpProxy.createServer({
    hostnameOnly: true,
    router: {
        'www.my-domain.com': '127.0.0.1:3001',
        'www.my-other-domain.de' : '127.0.0.1:3002'
    }
}).listen(80);

The problem is that I want to have for example app1.my-domain.com pointing to localhost:3001, app2.my-domain.com pointing to localhost:3002, and all other go to port 3000 for example, where my apache server will be running. I couldn't find anything in the documentation on how to have a "default" route.

Any ideas?

EDIT I want to do that because I have a lot of domains/subdomains handled by my apache server and I don't want to have to modify this routing table each time I have want to add a new subdomain.


Solution

  • For nearly a year, I had successfully used the accepted answer to have a default host, but there's a much simpler way now that node-http-proxy allows for RegEx in the host table.

    var httpProxy = require('http-proxy');
    
    var options = {
      // this list is processed from top to bottom, so '.*' will go to
      // '127.0.0.1:3000' if the Host header hasn't previously matched
      router : {
        'example.com': '127.0.0.1:3001',
        'sample.com': '127.0.0.1:3002',
        '^.*\.sample\.com': '127.0.0.1:3002',
        '.*': '127.0.0.1:3000'
      }
    };
    
    // bind to port 80 on the specified IP address
    httpProxy.createServer(options).listen(80, '12.23.34.45');
    

    The requires that you do NOT have hostnameOnly set to true, otherwise the RegEx would not be processed.