Virtual hosting with standalone node.js server

2019-01-10 10:16发布

问题:

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

回答1:

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

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



回答2:

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


回答3:

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.