0

I'm trying to get my Express app to redirect users to HTTPS when they visit the site on HTTP. I've looked at this question:

Automatic HTTPS connection/redirect with node.js/express

but it didn't quite have the answers I was looking for. I'm using httpolyglot:

https://github.com/mscdex/httpolyglot

because I want to do this on only one port, and httpolyglot is performing as advertised, but I can't get the redirect to work. Here's my code:

var express = require('express');
var https = require('https')
var gulp = require('gulp');
var fs = require('fs');
var httpolyglot = require('httpolyglot');
var app = express();
require('./gulpfile');

gulp.start('config');

const options = {
    key: fs.readFileSync("/path/to/key.key"),
    cert: fs.readFileSync("/path/to/cert.cer")
};

app.use(express.static(__dirname));
app.use(function(req, res) {
    if (!req.socket.encrypted) {
        res.writeHead(301, {'Location': 'https://' + req.host + req.url});
        return res.end()
    }
});

app.get('/landing', function(req, res) {
  res.sendFile(__dirname + '/landing.html');
});

// Defer all other routes to the angular app
app.use(function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

httpolyglot.createServer(options, app).listen(3004);
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Peter Weeks
  • 291
  • 2
  • 16

1 Answers1

0

Figured it out. My app.use function was in the code after some Express middleware that wasn't calling next(), so it wasn't getting called.

Peter Weeks
  • 291
  • 2
  • 16