ExpressJS多域https托管

时间:2016-07-02 16:14:22

标签: node.js express express-vhost

我有一个项目,我需要托管两个带有两个域的网站,这些域指向与EpressJS服务器相同的服务器(1个静态IP)。 在我的研究中,我发现,express可以用vhosts扩展。但我无法弄明白,如何使用它们与https。 我的愿望是有太多不同的快递对象,所以我可以通过appBar.get()或他们的POST或JSON-aquivalent通过appFoo.get()和'bar.com'请求访问'foo.com'请求。 我不想在apache,nginx oder节点本身使用代理。我想在端口80/443上运行它们。

1 个答案:

答案 0 :(得分:1)

// Includes
var https = require('https');
var express = require('express');
var tls = require('tls');
var vhost = require('vhost');
var fs = require('fs');


// Express objects
var appFoo = express();
var appBar = express();

// SSL Constants
const siteFoo = {
    app: appFoo,
    context: tls.createSecureContext({
        key: fs.readFileSync(__dirname + '/tls/foo.com/privkey.pem').toString(),
        cert: fs.readFileSync(__dirname + '/tls/foo.com/fullchain.pem').toString(),
        ca: fs.readFileSync(__dirname + '/tls/foo.com/chain.pem').toString()
    }).context
};

const siteBar = {
    app: appBar,
    context: tls.createSecureContext({
        key: fs.readFileSync(__dirname + '/tls/bar.com/privkey.pem').toString(),
        cert: fs.readFileSync(__dirname + '/tls/bar.com/fullchain.pem').toString(),
        ca: fs.readFileSync(__dirname + '/tls/bar.com/chain.pem').toString()
    }).context
};

// Sites
var sites = {
    'www.foo.com': siteFoo,
    'foo.com': siteFoo,

    'www.bar.com': siteBar,
    'bar.com': siteBar
}

// Setup vhosts
var exp = express();
for (var s in sites) {
    console.log("add app for " + s);
    exp.use(vhost(s, sites[s].app));
}

// Redirect from http port  to https
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
    console.log(req.headers['host']);
    console.log(req.url);
    res.end();
}).listen(80);

// HTTPS Server
var secureOpts = {
    SNICallback: function (domain, cb) {
        if (typeof sites[domain] === "undefined") {
            cb(new Error("domain not found"), null);
            console.log("Error: domain not found: " + domain);

        } else {
            cb(null, sites[domain].context);
        }
    },
    key: fs.readFileSync(__dirname + '/tls/qarm.de/foo.com/privkey.pem').toString(),
    cert: fs.readFileSync(__dirname + '/tls/qarm.de/foo.com/fullchain.pem').toString(),
    ca: fs.readFileSync(__dirname + '/tls/qarm.de/foo.com/chain.pem').toString()
};

var https = require('https');
var httpsServer = https.createServer(secureOpts, exp);
httpsServer.listen(443, function () {
    console.log("Listening https on port: " + + this.address().port);
});

appFoo.get('/', function(req,res) {
   res.send('Foo.com');
}

appBar.get('/', function(req,res) {
   res.send('bar.com');
}

此代码从新的快速对象创建两个单独的vhost,初始化TLS,将请求定向到正确的对象,并将所有流量从HTTP(端口80)重定向到HTTPS(443)