如何在AWS ELB后强制重定向到HTTPS

时间:2019-05-19 01:26:06  来源:igfitidea点击:

web服务器运行在端口80上,以监听AWS Ec2 instnace上的http连接。
然后配置AWS ELB侦听HTTP和HTTPS协议,并将所有请求转发到端口80上的后端服务器。
Amazon弹性负载均衡器(ELB)支持x - forward - proto头值,包括应用程序的协议。
本教程使用HTTP请求的x - forward - proto头值,如果客户端协议不是HTTPS,则应用重写规则。
这里是Apache, Nginx和IIS在AWS ELB后强制重定向到HTTPS的配置细节。

1。Apache

在文本编辑器中编辑Apache VirtualHost配置文件,并添加以下内容。
确保重写模块在Apache服务器中启用。

<VirtualHost *:80>
  ...
  RewriteEngine On
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI}
</VirtualHost>

2。Nginx

编辑你的域的Nginx HTTP服务器块来配置强制重定向。
在location块下添加以下内容,将所有http流量重定向到https。

server {
 listen 80;
 ...
 location / {
  if ($http_x_forwarded_proto != 'https') {
  rewrite ^ https://$host$request_uri? permanent;
  }
 }
}

3。IIS

windows服务器与IIS web服务器一起编辑web。
配置文件,并在下面添加以下代码:

<rewrite>
<rules>
<rule name="AWS ELB Forece Redirect to HTTPS" stopProcessing="true">
<match url="^(.*)$" ignoreCase="false" />
<conditions>
<add input="{HTTP_X_FORWARDED_PROTO}" pattern="^http$" ignoreCase="false" />
</conditions>
<action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}{REQUEST_URI}" />
</rule>
</rules>
</rewrite>