ExpressJS多域https托管



我有一个项目,在那里我需要托管两个网站与两个域,这指向相同的服务器(1静态IP)与一个EpressJS服务器。在我的研究过程中,我发现express可以用vhost进行扩展。但我不知道如何使用它们与https。我的愿望是有太不同的表达对象,所以我可以访问'foo.com'-请求appFoo.get()和'bar.com'-请求通过appBar.get()或他们的POST或json等同。我不想使用代理在apache, nginx奥德节点本身。我想在80/443端口上运行它们

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

相关内容

  • 没有找到相关文章

最新更新