Virtual hosting with standalone node.js server


Question

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

1
38
12/14/2011 11:37:48 AM

Accepted Answer

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

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

29
3/4/2013 11:37:02 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon