Redirection to https not working for homepage

I’m using express to serve static files on my vps. I created two servers http and https like so:

var httpServer = http.createServer(app);
httpServer.listen(port); // 3000

var httpsServer = https.createServer(credentials, app);
httpsServer.listen(3001);

They are redirected to correct ports via iptables but this is not the point.

By using a middlewear like below:

app.use(function (req, res, next) { 
    !req.secure 
        ? res.redirect(301, path.join('https://', req.get('Host'), req.url)) 
        : next();
});

All my requests are well redirected. However, when loading my website with only the domain without ssl (http://example.com) and without any child routes (like http://example.com/contact), this is not redirecting to https.

Can you help me to find out what I missed? If it is an issue or not?

Thank you. (I logged that question in stackoverflow as well: https://stackoverflow.com/questions/46024470/nodejs-express-redirection-to-https-not-working-for-homepage)

Author: Fantashit

1 thought on “Redirection to https not working for homepage

  1. I finally found out what was the issue: I was serving the public folder before the security test…

    So here are the steps now:

    // Step 1: Test all incoming requests (from http and https servers).
    
    app.use(function (req, res, next) {
        if (req.secure) 
            return next();
    
        var target = url.format({ // Thanks Linus for the advice!
            protocol: 'https:',
            host: req.hostname,
            pathname: req.url
        });
    
        res.redirect(301, target);
    });
    
    // Step 2: Serve static files.
    
    app.use(express.static(path.join(__dirname, 'your/dist/folder')));
    
    // Step 3: Build routes (in my case with * because of the SPA).
    
    app.get('*', function (req, res) {
        res.sendFile(path.join(__dirname, 'your/dist/folder', 'index.html'));
    });
    

    Now it is working perfectly!

Comments are closed.