Amit Dhamu

Software Engineer

Redirect to HTTPS in Express

This example uses Node directly for a web server. It assumes you are using port 80 for regular HTTP and 443 for HTTPS.


let express = require('express');
let app = express();
let http = require('http');
let https = require('https');
let fs = require('fs');

// Middleware which will perform the redirect
app.all('*', function(req, res, next) {
    if ( {
        return next();
    res.redirect('https://' + req.hostname + req.url);

// Setup your app to listen on both ports 80 and 443
    key: fs.readFileSync('path/to/key/file'),
    cert: fs.readFileSync('path/to/certificate/file'),
    ca: fs.readFileSync('path/to/chain/file')
}, app).listen(443);


In a production environment, it's probably more robust to use NGINX which would let you accomplish this without creating two servers. It's also worth noting that you'd have to modify your server to allow "Non-root port binding" or play with iptables if you were to use ports 80 and 443 directly from your Node app.

 node / express / http / https / ssl

Strip Trailing Slashes From Express RequestsClear Button On Input Field

Show Comments

Made with by Amit Dhamu.
© MMXX. All rights reserved.