Redirect nodejs express static request to https

喜欢而已 提交于 2020-02-03 10:09:09

问题


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?


回答1:


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);
});



回答2:


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




回答3:


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.




回答4:


This code redirects in effortless manner to either http / https

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


来源:https://stackoverflow.com/questions/39529265/redirect-nodejs-express-static-request-to-https

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!