繁体   English   中英

在Elastic Beanstalk上使用Node / Express重定向到HTTPS

[英]Redirect to HTTPS with Node/Express on Elastic Beanstalk

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

阅读了几篇文章,包括这篇文章后,下面的代码就是我想出来的。 不幸的是,这不起作用。

我错过了什么?

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;

事实证明,我只需要重新排序我的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;

代码中最明显的问题是HTTPS是从端口443提供的。此外,它看起来像过时的代码。 为什么不使用最新版本的Express? 如果你看一下HTTPS的例子,他们在这里给出了与你所写的完全不同的内容: http//expressjs.com/en/api.html搜索'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);

当我过去使用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)。 您可以将其替换为您想要获取端口的任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM