Astemir Almov
Astemir Almov

Reputation: 446

Redirect nodejs express static request to https

I need to redirect all http requests to https including request to static files.

My code:

app.use(express.static(__dirname + '/public'));

app.get('*', function(req, res) {
    if (!req.secure){
            return res.redirect('https://' + config.domain + ":" + config.httpsPort + req.originalUrl);
        }
    res.sendFile(__dirname + '/public/index.html');    
});

And redirect not working on static files. If I change order:

app.get(...);

app.use(...);

Then my static not working. How to redirect on such requests?

Upvotes: 4

Views: 5329

Answers (4)

Arun Panneerselvam
Arun Panneerselvam

Reputation: 2333

This code redirects in effortless manner to either http / https

res.writeHead(301, {
   Location: "http" + (req.socket.encrypted ? "s" : "") + "://" +    req.headers.host + loc,
});

Upvotes: 0

samith
samith

Reputation: 1160

function forceHTTPS(req, res, next) {
    if (!req.secure) {


        var hostname = req.hostname;


        var destination = ['https://', hostname,':', app.get('httpsPort'), req.url].join('');

        return res.redirect(destination);
    }
    next();
}


//For redirecting to https
app.use(forceHTTPS);

// For serving static assets
app.use(express.static(__dirname + directoryToServe));

The redirecting to https come before serving the static assets.

Upvotes: 0

Ishank Gulati
Ishank Gulati

Reputation: 655

var app = express();

app.all('*', function(req, res, next){
    console.log('req start: ',req.secure, req.hostname, req.url, app.get('port'));
    if (req.secure) {
        return next();
    }

    res.redirect('https://'+req.hostname + ':' + app.get('secPort') + req.url);
});

Upvotes: 5

Michael Troger
Michael Troger

Reputation: 3497

Have a look at the Node.js module express-sslify. It's doing exactly that - redirecting all HTTP requests so to use HTTPS.

You can use it like that:

var express = require('express');
var enforce = require('express-sslify');

var app = express();

// put it as one of the first middlewares, before routes
app.use(enforce.HTTPS()); 

// handling your static files just like always
app.use(express.static(__dirname + '/public'));

// handling requests to root just like always
app.get('/', function(req, res) {
   res.send('hello world');
});

app.listen(3000);

Documentation: https://github.com/florianheinemann/express-sslify

Upvotes: 0

Related Questions