4

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?

Astemir Almov
  • 396
  • 2
  • 16

4 Answers4

5
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);
});
Ishank Gulati
  • 633
  • 1
  • 8
  • 22
0

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

Michael Troger
  • 3,336
  • 2
  • 25
  • 41
  • My server working on two ports. First for http and second for https. And I need manually redirect to url with https port)) – Astemir Almov Sep 16 '16 at 12:24
0
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.

samith
  • 1,042
  • 8
  • 5
0

This code redirects in effortless manner to either http / https

res.writeHead(301, {
   Location: "http" + (req.socket.encrypted ? "s" : "") + "://" +    req.headers.host + loc,
});
Arun Panneerselvam
  • 2,263
  • 1
  • 17
  • 24