Virtual hosting with standalone node.js server

后端 未结 3 1986
失恋的感觉
失恋的感觉 2020-11-30 22:38

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

相关标签:
3条回答
  • 2020-11-30 23:04

    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);
    
    0 讨论(0)
  • 2020-11-30 23:16

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

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

    0 讨论(0)
  • 2020-11-30 23:18

    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.

    0 讨论(0)
提交回复
热议问题