Last Updated: February 25, 2016
·
11.89K
· alanthing

Default host with node-http-proxy

node-http-proxy is a simple way to create proxies based on hostname, URIs, or RegEx, to various port+IPs. If you're running multiple node.js applications on a single IP address, this is a great way to do it. The documentation doesn't clearly explain how to have a "default" site in case a someone visits your IP with an invalid Host name, might be helpful if you're reusing an old IP address with new hostnames. Recent versions of node-http-proxy allow for RegEx, so thankfully this is fairly simple:

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');

This can be an easy alternative to using Nginx if you're only looking to share an IP address with multiple applications.

BONUS: Want to run your proxy on port 80 without running as root?

sudo setcap cap_net_bind_service=+ep /path/to/your/node

(Source: http://technosophos.com/content/run-nodejs-apps-low-ports-without-running-root)

1 Response
Add your response

can you update the code here with the same logic as http-proxy is already updated and the code above doesn't work anymore

over 1 year ago ·