Global outage event
If you're experiencing issues with your AWS services, then please refer to the AWS Health Dashboard. You can find the overall status of ongoing outages, the health of AWS services, and the latest updates from AWS engineers.
如何在 ELB 经典负载均衡器上将 HTTP 流量重定向到 HTTPS?
我在我的弹性负载均衡 (ELB) 经典负载均衡器上使用 HTTP 和 HTTPS 侦听器。我的经典负载均衡器卸载了 SSL,且后端连接在单个 HTTP 端口(端口 80)上侦听。当我尝试将流量从 HTTP 重定向到 HTTPS(端口 443)时,我收到错误“ERR_TOO_MANY_REDIRECTS”。
简短描述
经典负载均衡器不支持将 HTTP 流量重定向到 HTTPS 的原生功能。要实现此功能,您必须在经典负载均衡器后面的 Web 服务器实例上配置重写规则。
在 Web 应用程序服务器上配置重写规则,以使用 X-Forwarded-Proto 标头并重定向 HTTP 请求。否则,重写规则可能会在您的经典负载均衡器与负载均衡器后面的实例之间创建重定向请求的无限循环。此类循环会导致错误“ERR_TOO_MANY_REDIRECTS”。
**注意:**应用程序负载均衡器支持重定向操作,可用于将 HTTP 流量重定向到 HTTPS。要使用此功能,请将您的经典负载均衡器迁移到应用程序负载均衡器。
解决方法
查看以下适用于 Apache、NGINX 和 IIS Web 服务器的示例配置。配置经典负载均衡器后面的 Web 服务器,使其使用 X-Forwarded-Proto 标头根据客户端使用的是 HTTP 还是 HTTPS 来定向流量。请务必向您的 Web 服务器添加重写规则,以便:
- 使用 HTTP 将客户端重定向到 HTTPS URL
- 使用 HTTPS 直接为客户端提供服务
**注意:**根据您的配置和用例修改以下示例配置。
Apache 服务器: 虚拟主机文件方法
最佳做法是使用以下方法来配置您的 Web 服务器:
-
打开您的 Apache 配置文件。可能的位置包括 /etc/httpd/conf/httpd.conf (Apache 2/httpd)、/etc/apache2/sites-enabled/ (Apache 2.4) 或 /etc/apache2/apache2.conf(Ubuntu 上的 Apache)。
-
在配置文件的 VirtualHost 部分中添加类似于以下内容的重写规则:
<VirtualHost *:80>RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} =http RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent] </VirtualHost> -
保存您的 Apache 配置文件。
-
重启 Apache。
Apache 服务器:.htaccess 文件方法
如果您无权访问 Apache 的主配置文件,请使用 .htaccess 文件。有关详细信息,请参阅 Apache 网站上的“Apache HTTP Server 教程:.htaccess 文件”页面中的“何时(不)使用 .htaccess 文件”部分。
要配置您的 Web 服务器,请完成以下步骤:
-
打开您的 Apache 配置文件。可能的位置包括 /etc/httpd/conf/httpd.conf (Apache 2/httpd) 或 /etc/apache2/sites-enabled/ (Apache 2.4)。
-
编辑 Directory 指令以打开 .htaccess:
<Directory "/var/www/html"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> -
保存您的 Apache 配置文件。
-
打开您的 .htaccess 文件。
-
添加类似于以下内容的重写规则:
RewriteEngine OnRewriteCond %{HTTP:X-Forwarded-Proto} =http RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent] -
保存您的 .htaccess 文件。
-
重启 Apache。
NGINX 服务器
**注意:**此解决方法适用于 NGINX 1.10.3 (Ubuntu) 和 NGINX 1.12.1 (Amazon Linux)。
完成以下步骤:
-
打开您的 NGINX 配置文件 (nginx.conf)。
-
添加以下重写规则。请务必根据您的配置修改重写规则:
server { listen 80; server_name _; if ($http_x_forwarded_proto = 'http'){ return 301 https://$host$request_uri; } } -
重启 NGINX。
IIS 服务器
**注意:**此解决方法适用于 Microsoft Windows Server 2012 R2 和 2016 Base。
完成以下步骤:
-
安装 IIS URL 重写模块。有关详细信息,请参阅 Microsoft 网站上的 URL rewrite(URL 重写)。
-
打开您的 web.config 文件。
-
在 <system.webServer> 部分中添加以下重写规则。根据您的具体配置修改重写规则:
<rewrite> <rules> <rule name="Rewrite HTTP to HTTPS" stopProcessing="true"> <match url="^(.*)$"/> <conditions logicalGrouping="MatchAny"> <add input="{HTTP_X_FORWARDED_PROTO}" pattern="^http$"/> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/> </rule> </rules> </rewrite> -
保存您的 web.config 文件。
-
打开 IIS 管理器。
-
刷新默认网站。
-
检查新的重写规则是否显示在 URL Rewrite(URL 重写)部分中。
-
重启您的网站。
-
验证您的重定向是否有效。
相关信息
- 语言
- 中文 (简体)

相关内容
AWS 官方已更新 4 年前