重定向nodejs向https表达静态请求

时间:2016-09-16 10:30:27

标签: javascript node.js redirect express https

我需要将所有http请求重定向到https,包括请求静态文件。

我的代码:

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

重定向无法处理静态文件。如果我改变订单:

app.get(...);

app.use(...);

然后我的静态不起作用。如何重定向此类请求?

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

查看Node.js模块express-sslify。它正是这样做的 - 重定向所有HTTP请求以便使用HTTPS。

你可以这样使用它:

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

文档:https://github.com/florianheinemann/express-sslify

答案 2 :(得分: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));

在提供静态资产之前,重定向到https。

答案 3 :(得分:0)

此代码以毫不费力的方式重定向到http / https

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