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

AWS环境下Nginx配置Http转Https时排除公网IPv4重定向问题

解决Nginx中访问公网IPv4被强制HTTPS重定向的问题

你的问题核心在于当前Nginx配置会对所有访问80端口的请求(包括直接访问公网IP的请求)执行HTTPS重定向,但直接访问公网IP时,HTTPS是不可用的——毕竟你的ACM证书绑定的是域名而非IP,最终导致访问失败。下面给你两种针对性的解决方案,按需选择即可:

方案一:仅对域名请求执行HTTPS重定向

这种方式更通用,只在请求的Host头匹配你的域名时才触发重定向,对公网IP的请求直接转发到后端服务:

server {
    listen 80;
    server_name mysite.com www.mysite.com;

    location / {
        # 仅当请求Host是指定域名时,才检查协议并执行重定向
        if ($host ~* ^(mysite.com|www.mysite.com)$) {
            if ($http_x_forwarded_proto != 'https') {
                rewrite ^ https://$host$request_uri? permanent;
            }
        }
        # 公网IP访问等其他情况,直接转发到后端
        proxy_pass http://172.x1.x5.xx6:8080;
        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;
        proxy_redirect off;
    }
}

方案二:直接排除公网IP的重定向逻辑

如果你明确知道自己的公网IPv4地址,可以直接把它加入排除条件,当请求的Host是该IP时跳过重定向:

server {
    listen 80;
    server_name mysite.com www.mysite.com;

    location / {
        # 替换成你的实际公网IPv4,匹配到则跳过重定向
        if ($host != 'xxx.xxx.xxx.xxx') {
            if ($http_x_forwarded_proto != 'https') {
                rewrite ^ https://$host$request_uri? permanent;
            }
        }
        proxy_pass http://172.x1.x5.xx6:8080;
        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;
        proxy_redirect off;
    }
}

配置生效步骤

修改完配置后,记得重启Nginx让变更生效:

sudo systemctl restart nginx

之后你可以测试两种访问场景:

  • 访问mysite.com或www.mysite.com:会正常重定向到HTTPS
  • 直接访问公网IPv4:会通过HTTP直接访问后端服务,不再触发无效的HTTPS跳转

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:13:43