node.js - EC2 Ubuntu NGINX 配置 HTTPS 重定向给我错误 : ERR_TOO_MANY_REDIRECTS

标签 node.js express ubuntu amazon-ec2 nginx-reverse-proxy

背景
我有一台在 AWS EC2 实例(Node/Express 应用程序)上运行的 Ubuntu 机器,其 SSL 证书设置使用证书管理器和负载均衡器。这适用于使用 https 直接访问我的网站,例如 https://example.com .但是,使用 http ,导致连接不安全。
检查whynopadlock.com,我被告知我的网络服务器没有强制使用HTTPS。我的 Web 服务器设置为使用 NGINX 作为我的 EC2 实例的私有(private) IP 的反向代理。我四处寻找,似乎找不到像我这样合适的例子,尽管我试图拼凑我能找到的东西。
当我尝试设置强制 HTTPS 重定向时,我得到 ERR_TOO_MANY_REDIRECTS .
之前:原始 Nginx 配置

server {
    listen 80;
    location / {
        proxy_pass http://{{MASKED_EC2_INSTANCE_PRIVATE_IP_FOR_POST}}:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Notes: This config allowed https://example.com to load fine, however there was no redirect if navigating to the site using http://example.com and resulted an insecure connection.


之后:添加 HTTPS 重定向后的 NGINX 配置
# HTTP
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    return 301   https://$host$request_uri;
}

# HTTPS
server {
    listen       443 default_server;
    listen       [::]:443 default_server;
    server_name  localhost;

    location / {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass https://{{MASKED_EC2_INSTANCE_PRIVATE_IP_FOR_POST}}:8000;
        proxy_set_header X-Forwarded-Proto https;
    }
}
问题
我现在看到,当我使用 http 加载域时,我被成功重定向到 https ,但是我收到错误 ERR_TOO_MANY_REDIRECTS .
任何人都可以帮助我了解我缺少什么或在我的配置中可能做错了吗?

最佳答案

由于您使用的是 ALB,您可以 在 ALB 上将 http 重定向到 https 本身。 AWS 提供了如何设置的指南:

How can I redirect HTTP requests to HTTPS using an Application Load Balancer?


该过程涉及创建 http 监听器并添加 重定向操作 到它而不是常规的转发规则。这样您就不必对实例执行任何更改,因为所有这些都由 ALB 负责。
此外,由于您使用的是 AWS Certificate Manager,因此您必须使用 ALB,因为 ACM SSL 证书不能在实例上使用。 ACM 只能用于负载均衡器(ALB、CLB 或 NLB)、CloudFront 发行版或 API 网关。

关于node.js - EC2 Ubuntu NGINX 配置 HTTPS 重定向给我错误 : ERR_TOO_MANY_REDIRECTS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65535286/

相关文章:

node.js - 使用node.js和localhost html客户端连接socket.io.js错误

javascript - 让 CORS 与 JQuery 客户端、Node/Express 服务器一起使用时出现问题

node.js - 将 Node js 应用程序部署到 Heroku

php - 安装 apache2 后启动 Apache HTTP 服务器失败

c# - Ubuntu - 运行 dotnet new 控制台时出现段错误错误

node.js - 如何在 View 中一致地访问用户是否经过身份验证

node.js - Sails.js 中的唯一属性失败

javascript - 如何在 NodeJS/Javascript 中进行长轮询?

node.js - 如何避免使用 discord.js api 超过速率限制?

linux - AWK 在 Bash 中返回/打印为关联数组