【问题标题】:Express vhosts + https快速虚拟主机 + https
【发布时间】:2017-09-22 22:26:06
【问题描述】:

有什么方法可以使用 https 在 Express 上运行虚拟主机?我当前的代码(非 SSL)如下所示:

var express = require('express');
var vhost = require('vhost');
var path = require('path');

var appOne = express();
var appTwo = express();
var appVhosts = module.exports = express();

appOne.use(express.static(path.join(__dirname, 'pages')));

appTwo.get('/', function(req, res){
    res.send('That service isn\'t up right now!')
});

app.use(vhost('siteone.com', appOne));
app.use(vhost('sitetwo.com', appTwo));

appVhosts.listen(80);

不过,据我所知,https 模块只接受一个 ssl 证书。

【问题讨论】:

    标签: node.js express https vhosts express-vhost


    【解决方案1】:

    显然,https.Server 继承自 tls.Server,后者提供了一个名为 addContext() 的方法。您可以在那里配置多个证书。我还编写了一个非常小的包,使用这种方法来实现结果,https://www.npmjs.com/package/vhttps。你可以在那里查看我的实现。

    【讨论】:

    • 这很好用,而且比端口重新路由要容易得多! :D
    【解决方案2】:

    您需要为每个应用定义 SSL 选项并分配给每个应用,如下所示:

    // (A) read SSL files
    var fs = require('fs');
    var appOneSSLOps = {
      key:  fs.readFileSync('./path_to_file/private.key'),
      cert: fs.readFileSync('./path_to_file/certificate.crt')
    }
    var appTwoSSLOps = {
      key:  fs.readFileSync('./path_to_file/private2.key'),
      cert: fs.readFileSync('./path_to_file/certificate2.crt')
    }
    
    // (B) assign SSL files to app
    var https = require('https');
    var appOneServer = https.createServer(appOneSSLOps , appOne).listen(443);
    var appTwoServer = https.createServer(appTwoSSLOps , appTwo).listen(80);
    
    // (C) route 80 to 443 - > on your machine route port 80 to 443 either manually or by child_process: I assume you are using linux Ubuntu System
    childProcess = require('child_process');
    var optionExec = {timeout: 3000}; //option(s) for childProcess.exec
    childProcess.exec(
      'sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 443',
      optionExec,
      function(err, stdout, stderr) {
    
      }
    );
    
    // (D) then enforce SSL - I assume appOne is the main app.
    appOne.use(function(request, response, next) {
      if(!request.secure) {
        response.redirect('https://' + request.headers.host + request.url);
      }
      next();
    });
    

    注意:我假设 appOne 是主应用程序。

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2018-03-23
      • 2016-02-26
      • 2016-07-28
      • 2018-09-23
      • 2017-04-08
      • 2010-10-07
      • 1970-01-01
      • 2016-07-16
      相关资源
      最近更新 更多