【问题标题】:Redirect to HTTPS with Node/Express on Elastic Beanstalk在 Elastic Beanstalk 上使用 Node/Express 重定向到 HTTPS
【发布时间】:2023-03-09 15:05:02
【问题描述】:

我正在尝试让网站强制使用 HTTPS(从 HTTP 重定向)。我们已经通过 AWS Elastic Beanstalk 设置了 HTTPS。问题是目前HTTP和HTTPS都可以使用。

在阅读了一些帖子后,包括this one,下面的代码就是我想出的。不幸的是,这不起作用。

我错过了什么?

import express from 'express';
import { join } from 'path';

const app = express();
const buildPath = join(`${__dirname}/../build`);
const enforceHTTPS = (req, res, next) => {
  if (req.headers['x-forwarded-proto'] === 'https') return next();
  else return res.redirect(301, join(`https://${req.hostname}${req.url}`));
};

app.use(express.static(buildPath));
app.use(enforceHTTPS);
app.get('*', (req, res) => res.sendFile(`${buildPath}/index.html`));
app.listen(process.env.PORT || 3000, () => console.log('Server running on port 3000!'));

export default app;

【问题讨论】:

  • 我认为您可以使用 aws 在您的节点端将所有 https 请求代理到 http。保持节点在 http 上运行。否则按照建议将 https 服务器与 express 一起使用。

标签: javascript node.js express https amazon-elastic-beanstalk


【解决方案1】:

事实证明,我只需要重新排序我的 app.use 语句——在为静态文件提供服务之前调用重定向

此外,为了在 IE/Edge 上运行,需要将“https://”移到 path.join 之外(join 删除了第二个正斜杠,尽管所有其他主流浏览器都会正确处理它, IE 不喜欢它)。

这是一个工作示例:

import express from 'express';
import { join } from 'path';

const app = express();
const buildPath = join(`${__dirname}/../build`);
const enforceHTTPS = (req, res, next) => {
  if (req.headers['x-forwarded-proto'] === 'https') return next();
  return res.redirect(301, `https://${join(req.hostname, req.url)}`);
};

app.use(enforceHTTPS);
app.use(express.static(buildPath));
app.get('*', (req, res) => res.sendFile(`${buildPath}/index.html`));
app.listen(process.env.PORT || 3000, () => console.log('Server running on port 3000!'));

export default app;

【讨论】:

    【解决方案2】:

    当我过去使用 node.js 作为代理时,我们获得代理到安全的不安全连接的方式如下,已修改以匹配您的代码:

    const httpsPort = process.env.HTTPS_PORT;
    
    app.use(function(req, res, next) {
        if (req.secure) {
            return next();
        }
        res.redirect(301, ['https://', req.hostname, ':', httpsPort, '/', req.url].join('');
    }
    

    httpsPort 是您的标准 https 连接将通过的端口。 process.env.HTTPS_PORT 将获取 https 端口的环境变量(标准为 443)。你可以用任何你想要的端口来替换它。

    【讨论】:

      【解决方案3】:

      您的代码中最明显的问题是 HTTPS 从端口 443 提供服务。此外,这看起来像是过时的代码。为什么不使用最新版本的 Express?如果您查看 HTTPS 的示例,他们在这里给出的内容与您所写的完全不同:http://expressjs.com/en/api.html search for 'HTTPS'

      var express = require('express');
      var https = require('https');
      var http = require('http');
      var app = express();
      
      http.createServer(app).listen(80);
      https.createServer(options, app).listen(443);
      

      【讨论】:

      • 我没有尝试在应用程序端使用 Express 设置 HTTPS 服务器 - 它已经通过 AWS Elastic Beanstalk 设置。我正在尝试将 HTTP 流量重定向到 HTTPS。
      • 这在AWS上不行,我试过了!
      猜你喜欢
      • 2014-07-05
      • 2016-06-19
      • 2018-02-16
      • 2017-09-20
      • 2018-01-01
      • 2017-02-27
      • 2019-10-29
      • 2021-02-23
      • 2019-01-24
      相关资源
      最近更新 更多