2017-04-25 144 views
2

有什麼辦法可以在Express上使用https運行虛擬主機?我當前的代碼(非SSL)看起來是這樣的:Express vhosts + https

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證書。

回答

0

您需要定義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是主要的應用程序。

0

顯然,https.Server繼承自tls.Server,它提供了一種稱爲addContext()的方法。您可以在那裏配置多個證書。我也寫了一個非常小的包,使用這種方法來實現結果,https://www.npmjs.com/package/vhttps。你可以在那裏檢查我的實現。