3

Is there a way to set up a custom port for SSL on Express? This is for development purposes only. I have one Apache/PHP project on 80/443.

I've tried following this tutorial http://www.hacksparrow.com/express-js-https.html

But honestly I can't get that to work. If someone could post the correct way to configure Express to do this, that would be AWESOME. Here's my server config:

var hskey = fs.readFileSync('mywebsite-key.pem');
var hscert = fs.readFileSync('mywebsite-cert.pem')
var options = {
    key: hskey,
    cert: hscert
};

//Create server
var app = express(options);

// Configure server
app.configure(function () {
    //parses request body and populates request.body
    app.use(express.bodyParser());
    //checks request.body for HTTP method overrides
    app.use(express.methodOverride());
    //perform route lookup based on url and HTTP method
    app.use(app.router);
    //Where to serve static content
    app.use(express.static(path.join(application_root, 'public')));
    //Show all errors in development
    app.use(express.errorHandler({
        dumpExceptions: true,
        showStack: true
    }));
});


//Start server
var port = nconf.get('port');;
var server = require('http').createServer(app),
    io = require('socket.io').listen(server);
server.listen(port, function () {

    console.log('Express server listening on port %d in %s mode', port, app.settings.env);
});
metalaureate
  • 7,572
  • 9
  • 54
  • 93

1 Answers1

5

You are initialising the server wrong. Firstly you are using require('http') for the server so it will not use the SSL options. Secondly you are passing the certificate options to express, instead of the https server.

You have to do it like this:

var hskey = fs.readFileSync('mywebsite-key.pem');
var hscert = fs.readFileSync('mywebsite-cert.pem')
var options = {
    key: hskey,
    cert: hscert
};
var express = require('express'),
    app = express()
  , https = require('https')
  , server = https.createServer(options,app)
  , io = require('socket.io').listen(server);

// listen for new web clients:
server.listen(8080);
user568109
  • 47,225
  • 17
  • 99
  • 123
  • Fantastic, thank you! Could you help me with one last step - how do I redirect any http traffic to https? – metalaureate Jul 16 '13 at 15:14
  • 1
    See this answer http://stackoverflow.com/a/7458587/568109. You can do it completely via node.js, but it would require two servers. iptables may be more efficient. – user568109 Jul 16 '13 at 15:36