redirect HTTP to HTTPS using express

I am trying to redirect all HTTP traffic to HTTPS using my express server. I am running the server on AWS lightsail Mean stack. I have tried setting auto redirect from HTTP to HTTPS when I set up my SSL on lets-encrypt but that didn’t work. I can’t set the redirect on apache because I am using ports 80 and 443 with express so I have to disable apache. So I tried to come up with something for the redirection using only express. Below is a code I tried. Basically what I did was listen to all traffic on port 80 and redirect them to HTTPS but this method isn’t working too. Is there a way to redirect HTTP to HTTPS using express? Thanks in advance.

'use strict';
const express = require('express')
const http = require('http')
const https = require('https')
const fs = require('fs')
const path = require('path')
const cookie = require('cookie-parser')

const domain = 'mydomain.com'

const app = express()

app.use('/js', express.static(__dirname + '/public/js'))
app.use('/css', express.static(__dirname + '/public/css'))
app.set('view engine', 'ejs')
app.set('views', './views')
app.use(cookie())
app.use(express.json({ limit: '50mb' }));

app.use('/', require('./routes/pages'))
app.use('/api', require('./controllers/auth'))

app.get('*',function(req, res){
    res.redirect('https://' + domain + req.path);
});

http.createServer(app).listen(80, function(){
    console.log('HTTP listening on port 80');
});

const appSecure = express();

appSecure.use('/js', express.static(__dirname + '/public/js'))
appSecure.use('/css', express.static(__dirname + '/public/css'))
appSecure.set('view engine', 'ejs')
appSecure.set('views', './views')
appSecure.use(cookie())
appSecure.use(express.json({ limit: '50mb' }));

appSecure.use('/', require('./routes/pages'))
appSecure.use('/api', require('./controllers/auth'))

var options = {
  key: fs.readFileSync('/home/bitnami/htdocs/letsencrypt/certificates/www.mydomain.com.key'),
  cert: fs.readFileSync('/home/bitnami/htdocs/letsencrypt/certificates/www.mydomain.com.crt'),
};

https.createServer(options, appSecure).listen(443, function(){
    console.log('HTTPS listening on port 443');
});

>Solution :

All, you need for the http server is this:

const domain = 'mydomain.com';
const app = express();
// redirect every single incoming request to https
app.use(function(req, res) {
    res.redirect('https://' + domain + req.originalUrl);
});
app.listen(80);

You don’t want all your other route handlers on the http server because what you want to do is just redirect any http:// URL immediately to the https:// version of the URL and you never serve any content from the http URL.

Note, this also uses req.originalUrl in constructing the redirect URL because that will include any query parameters too.

Leave a Reply