Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express vhosts + https

Is there any way I can run vhosts on Express with https? My current code (non-SSL) looks like this:

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

However, as far as I know, the https module only accepts one ssl cert.

like image 859
Flora Rosenkreuz Avatar asked Oct 18 '25 12:10

Flora Rosenkreuz


2 Answers

Apparently, https.Server inherits from tls.Server, which offers a method called addContext(). You can configure multiple certificates there. I also wrote a very small package that uses this method to achieve the result, https://www.npmjs.com/package/vhttps . You can check my implementation there.

like image 99
Kevin Qian Avatar answered Oct 21 '25 01:10

Kevin Qian


You need to define SSL Options for each app and assign to each app as follows:

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

Note: I assume appOne is the main app.

like image 35
Ghsy Avatar answered Oct 21 '25 02:10

Ghsy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!