1

我有一个项目,我需要托管两个具有两个域的网站,它们指向具有 EpressJS 服务器的同一服务器(1 个静态 IP)。在我的研究中,我发现 express 可以通过虚拟主机进行扩展。但我不知道如何将它们与 https 一起使用。我的愿望是有太多不同的快递对象,这样我就可以通过 appFoo.get() 访问“foo.com”请求,并通过 appBar.get() 或它们的 POST 或 JSON-aquivalent 访问“bar.com”请求。我不想在 apache、nginx oder 节点本身中使用代理。我想在端口 80/443 上运行它们。

4

1 回答 1

2
// 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');
}

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

于 2016-12-28T20:39:40.753 回答