How to force SSL / https in Express.js

后端 未结 8 1706
小鲜肉
小鲜肉 2020-11-27 11:54

I am trying to create a middleware for Express.js to redirect all non-secure (port 80) traffic to the secured SSL port (443). Unfortunately there is no information in an Exp

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 12:33

    Although the question looks a year old, I would like to answer as it might help others. Its actually really simple with the latest version of expressjs (2.x). First create the key and cert using this code

    openssl genrsa -out ssl-key.pem 1024

    $ openssl req -new -key ssl-key.pem -out certrequest.csr .. bunch of prompts

    $ openssl x509 -req -in certrequest.csr -signkey ssl-key.pem -out ssl-cert.pem

    Store the cert and key files in the folder containing app.js. Then edit the app.js file and write the following code before express.createServer()

    var https = require('https');
    var fs = require('fs');
    
    var sslkey = fs.readFileSync('ssl-key.pem');
    var sslcert = fs.readFileSync('ssl-cert.pem')
    
    var options = {
        key: sslkey,
        cert: sslcert
    };
    

    Now pass the options object in the createServer() function

    express.createServer(options);
    

    Done!

提交回复
热议问题