将HTTP转发到HTTPS - AWS Windows Node.js

时间:2017-02-28 23:21:21

标签: node.js http amazon-ec2 https window

我有一个在AWS Windows和Node.js上运行的应用程序。我可以使用http和https访问。但如果有人通过http访问,我需要它将http转发到https。 我可以想到很多方面,但会对最佳方法的任何建议表示赞赏。服务器是EC2实例,可通过负载均衡器访问。

1 个答案:

答案 0 :(得分:1)

如果您使用快递,此中间件模块可以轻松实施https:https://www.npmjs.com/package/express-force-ssl

如果您在应用程序前面使用反向代理(ELB,nginx等),则需要设置信任代理设置。

以下是没有上述模块的示例:

    // Forward all requests to HTTPS.
    // enable reverse proxy support in Express. This causes the
    // the "X-Forwarded-Proto" header field to be trusted so its
    // value can be used to determine the protocol. See
    // http://expressjs.com/api#app-settings for more details.
    app.enable('trust proxy');

    // Add a handler to inspect the req.secure flag (see
    // http://expressjs.com/api#req.secure). This allows us
    // to know whether the request was via http or https.
    app.use((req, res, next) => {
      if (req.secure) {
        // request was via https, so do no special handling
        next();
      } else {
        // request was via http, so redirect to https
        console.log('Redirecting to https');
        res.redirect('https://' + req.headers.host + req.url);
      }
    });

完整示例app.js

var express = require('express');
var app = express();

// Forward all requests to HTTPS.
// enable reverse proxy support in Express. This causes the
// the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See
// http://expressjs.com/api#app-settings for more details.
app.enable('trust proxy');

// Add a handler to inspect the req.secure flag (see
// http://expressjs.com/api#req.secure). This allows us
// to know whether the request was via http or https.
app.use((req, res, next) => {
    if (req.secure) {
        // request was via https, so do no special handling
        next();
    } else {
        // request was via http, so redirect to https
        console.log('Redirecting to https');
        res.redirect('https://' + req.headers.host + req.url);
    }
});

// Respond to any GET requests with our message
app.get('*', (req, res) => {
    res.send('This is only served over https');
});

// Listen on the assigned port
var port = process.env.PORT || 3001;
app.listen(port);
console.log('Hello started on port ' + port);

仅重定向GET请求,对非GET请求响应错误

  app.all('*', (req, res, next) => {
    if (req.secure) {
      next();
    } else if (req.method === 'GET') {
      res.redirect(`https://${req.headers.host}${req.url}`);
    } else {
      res.status(401).send('Secure channel required');
    }
  });