You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Elastic Beanstalk单实例环境中实现HTTP到HTTPS的重定向

问题原因

你遇到的HTTP重定向不生效的核心原因是:Amazon Linux 2版本的Elastic Beanstalk默认Nginx配置已经存在一个监听80端口的server块,你在conf.d目录下新增的同端口server块属于重复配置,Nginx启动时会优先加载默认配置,导致你写的重定向规则完全没有生效。

解决方案

以下提供两种可选修复方案:


方案1:全量覆盖Nginx主配置(推荐,逻辑清晰无冲突)

直接替换EB默认的Nginx主配置,完全自定义转发规则:

  1. 在项目根目录下创建文件 .platform/nginx/nginx.conf,内容如下:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # HTTP自动重定向规则
    server {
        listen 80;
        return 301 https://$host$request_uri;
    }

    # HTTPS服务配置
    server {
        listen 443 ssl;
        ssl_certificate      /etc/pki/tls/certs/server.crt;
        ssl_certificate_key  /etc/pki/tls/certs/server.key;
        
        ssl_session_timeout  5m;
        
        ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers   on;
        
        location / {
            proxy_pass  http://localhost:5000;
            proxy_set_header   Connection "";
            proxy_http_version 1.1;
            proxy_set_header        Host            $host;
            proxy_set_header        X-Real-IP       $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto https;
        }
    }

    include /etc/nginx/conf.d/*.conf;
}
  1. 删除你之前创建的 .platform/nginx/conf.d/https.conf 文件,避免配置重复冲突。

方案2:增量修改默认配置(不需要全量覆盖)

如果你不想替换整个主配置,可以直接给默认的80端口规则加重定向逻辑:

  1. 在 .platform/nginx/conf.d/ 目录下新建文件 redirect.conf,内容如下:
if ($http_x_forwarded_proto = 'http') {
    return 301 https://$host$request_uri;
}
  1. 你之前写的HTTPS配置可以保留在原https.conf文件中,不需要修改。

验证步骤
  • 重新打包应用部署到EB环境,确保.platform目录在部署包的根目录,不是子目录
  • 部署完成后可以SSH到EB实例,执行sudo nginx -t检查配置语法是否正确
  • 执行sudo systemctl reload nginx加载新配置
  • 清除浏览器缓存后访问HTTP地址,验证重定向是否生效

内容的提问来源于stack exchange,提问作者Paras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:27:04