【问题标题】:Redirect nodejs express static request to https将nodejs express静态请求重定向到https
【发布时间】:2017-01-24 13:14:19
【问题描述】:

我需要将所有 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(...);

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

【问题讨论】:

    标签: javascript node.js redirect express https


    【解决方案1】:

    查看 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

    【讨论】:

    • 我的服务器在两个端口上工作。第一个用于 http,第二个用于 https。我需要使用 https 端口手动重定向到 url))
    【解决方案2】:
    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);
    });
    

    【讨论】:

    • 非常感谢。像魅力一样工作。
    【解决方案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));
    

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

    【讨论】:

      【解决方案4】:

      此代码以轻松的方式重定向到 http / https

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

      【讨论】:

        猜你喜欢
        • 2017-07-15
        • 2015-03-02
        • 1970-01-01
        • 2016-10-23
        • 1970-01-01
        • 2013-04-06
        • 2019-09-08
        • 1970-01-01
        • 2018-09-15
        相关资源
        最近更新 更多