Javascript 通过Elastic Beanstalk上的Node/Express重定向到HTTPS
我正试图让一个站点强制使用HTTPS(从HTTP重定向)。我们已经通过AWS Elastic Beanstalk设置了HTTPS。问题是,目前,HTTP和HTTPS都可以使用 在阅读了一些帖子之后,包括,下面的代码就是我想到的。不幸的是,这不起作用 我错过了什么Javascript 通过Elastic Beanstalk上的Node/Express重定向到HTTPS,javascript,node.js,express,https,amazon-elastic-beanstalk,Javascript,Node.js,Express,Https,Amazon Elastic Beanstalk,我正试图让一个站点强制使用HTTPS(从HTTP重定向)。我们已经通过AWS Elastic Beanstalk设置了HTTPS。问题是,目前,HTTP和HTTPS都可以使用 在阅读了一些帖子之后,包括,下面的代码就是我想到的。不幸的是,这不起作用 我错过了什么 import express from 'express'; import { join } from 'path'; const app = express(); const buildPath = join(`${__dirnam
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;
代码中最明显的问题是HTTPS是从端口443提供的。此外,这看起来像是过时的代码。为什么不使用最新版本的Express?如果你看一看他们在这里给出的HTTPS示例,它与你写的非常不同:搜索“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\u PORT
将获取HTTPS端口的环境变量(标准为443)。你可以用你想要的任何端口来替换它。事实证明,我只需要重新排序我的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;
我不想在应用程序端用Express设置HTTPS服务器——它已经通过AWS Elastic Beanstalk设置好了。我正在尝试将HTTP流量重定向到HTTPS。我认为您可以使用aws在节点端将所有HTTPS请求代理到HTTP。保持节点在http上运行。否则,请按照建议将https服务器与express一起使用。