44

Is there a way to currently do virtual hosting with node.js server (i.e. host multiple domains under one IP) ?

3 Answers 3

31

Sure, you can use bouncy or node-http-proxy specifically for that.

There's also an Express solution. Check out this example.

4
  • The github links gives me a 404
    – lpdahito
    Commented Oct 17, 2012 at 1:01
  • 1
    Try github.com/visionmedia/express/blob/master/examples/vhost/… now instead :) Commented Oct 20, 2012 at 18:44
  • Read this, just setup node-http-proxy and I love it. I use it on my local dev machine, where I'm now running 3 different node apps for actual use in-hose. It was easy to setup, and seemed to be the most mature, though bouncy didn't look bad, but the fact node-http-proxy called out supporting WebSockets and other goodies did it for me. Commented Nov 12, 2013 at 21:30
  • I notice the Express example does a redirect. in the example vhost provides they overwrite the value or req.url instead, but that doesn't seem to work for me. however, I prefer it because redirect displays the new url on the browser and I want to keep the old url. any thoughts as to why that might be?
    – ekkis
    Commented Nov 8, 2016 at 22:37
21

Web browsers send a the header property 'host' which identifies the domain host they are trying to contact. So the most basic way would be to do:

http = require('http');

server = http.createServer(function(request, response) {
    switch(request.headers.host) {
        case 'example.com': response.write('<h1>Welcome to example.com</h1>'); break;
        case 'not.example.com': response.write('<h1>This is not example.com</h1>'); break;
        default: 
            response.statusCode = 404;
            response.write('<p>We do not serve the host: <b>' + request.headers.host + '</b>.</p>');
    }
    response.end();
});
server.listen(80);
1
  • 1
    This is the simplest explanation of what a virtual server/virtual host actually is. It's just about using the "Host:" header as a piece of routing information. So simple. Of course https and SNI make it a bit more interesting...
    – masterxilo
    Commented Sep 13, 2018 at 13:45
6

I would recomend express-vhost because the others solutions are based on a proxy server, it means that each one of you vhost should open a different port.

Not the answer you're looking for? Browse other questions tagged or ask your own question.