How do I host multiple Node.js sites on the same IP/server with different domains?

前端 未结 12 873
轻奢々
轻奢々 2020-11-28 01:03

I have a linux server with a single IP bound to it. I want to host multiple Node.js sites on this server on this IP, each (obviously) with a unique domain or subdomain. I wa

12条回答
  •  悲&欢浪女
    2020-11-28 01:13

    I have an API I use on a site and below is my configuration. I also have it with SSL and GZIP, if someone needs it, just comment me.

    var http = require('http'),
        httpProxy = require('http-proxy');
    
    var proxy_web = new httpProxy.createProxyServer({
            target: {
                host: 'localhost',
                port: 8080
            }
        });
    
        var proxy_api = new httpProxy.createProxyServer({
            target: {
                host: 'localhost',
                port: 8081
            }
        });
    
        http.createServer(function(req, res) {
            if (req.headers.host === 'http://www.domain.com') {
                proxy_web.proxyRequest(req, res);
                proxy_web.on('error', function(err, req, res) {
                    if (err) console.log(err);
                    res.writeHead(500);
                    res.end('Oops, something went very wrong...');
                });
            } else if (req.headers.host === 'http://api.domain.com') {
                proxy_api.proxyRequest(req, res);
                proxy_api.on('error', function(err, req, res) {
                    if (err) console.log(err);
                    res.writeHead(500);
                    res.end('Oops, something went very wrong...');
                });
            }
        }).listen(80);
    

提交回复
热议问题