我有一个在awec ec2实例容器上运行的dockerized node.js / express应用程序。现在,我的应用程序在aws路由53托管的域名上运行。当我转到该域名时,使用的协议为http。如何为AWS EC2中在docker上运行的node.js服务器设置https?
这是我到目前为止所做的。
现在这就是我被卡住的地方。从this documentation中可以看到,我需要服务器中的证书副本,才能与服务器一起使用https。
我是新兵。如果您可以从一开始就逐步概述您的答案,将不胜感激。我有一个由AWS Route53托管域名访问的AWS EC2实例容器上运行的dockerized node.js / express应用程序。从这里如何将默认的连接协议从http更改为https?
答案 0 :(得分:0)
Elastic Load Balancer足以将额外的请求标头附加到请求(x-forwarded-proto),它告诉我们请求源自哪个协议。我们可以在Express中间件中使用它来进行重定向:
function forceHttps(req, res, next) {
const xfp =
req.headers["X-Forwarded-Proto"] || req.headers["x-forwarded-proto"];
if (xfp === "http") {
res.redirect(301, `https://${hostname}${req.url}`);
} else {
next();
}
}
server.use(forceHttps);
或使用npm软件包 https://www.npmjs.com/package/@crystallize/elasticloadbalancer-express-force-https
const express = require('express');
const forceHttps = require('@crystallize/elasticloadbalancer-express-force-https');
const server = express();
server.use(forceHttps());