namko
namko

Reputation: 647

Nodejs Express https to http redirect not working

I installed an SSL certificate on my Nodejs server.

const fs = require('fs');
const https = require('https');
const app = require('express');

https.createServer({
    key: fs.readFileSync('./ssl/private.key'),
    ca:fs.readFileSync('./ssl/ca_bundle.crt'),
    cert: fs.readFileSync('./ssl/certificate.crt')
}, app).listen(443);

Port 443 is the default listening for for https and port 8080 is the default listening port for http. My server is working fine and I can do https://www.example.net to access my site. But if I remove https or replace it with http , I wanted my server to auto redirect to https so I added:

app.use (function (req, res, next) {
    if (req.secure) {
            // request was via https, so do no special handling
            console.log(`Secure request`)
            next();
    } else {
            // request was via http, so redirect to https
            console.log(`Unsecure request`)
            res.redirect('https://' + req.headers.host + req.url);
    }
});

I can still connect file with https but if I remove it I get:

> dial tcp 312.312.d12.213:80: connectex: A connection attempt failed
> because the connected party did not properly respond after a period of
> time, or established connection failed because connected host has
> failed to respond.

Upvotes: 1

Views: 729

Answers (1)

namko
namko

Reputation: 647

I had to add

http.createServer(app).listen(80);

so that it can listen to unsecure request as well

Upvotes: 2

Related Questions