使用 AWS 的 ELB 从 Http 重定向到 Https

Redirecting from Http to Https with AWS's ELB

我在 之前查询过。我认为它在工作,但实际上还没有。

我有面向 Internet 的负载均衡器,后面是 Ec2 实例。 我的负载均衡器打开了 80 端口和 443 端口。

它们排列为 80 -> 80 和 443 -> 80。

现在我需要将 http 访问重定向到 https。

我做的是 我制作了一个 .htaccess 文件并位于 /var/www/html/ 中。那是我网站 index.php 所在的文件夹。

在.htaccess 文件中,我尝试了几个我在网上找到的版本。 None 他们工作了。

<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteCond %{HTTP_USER_AGENT} !^ELB-HealthChecker
    RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
</VirtualHost>

<VirtualHost *:80>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} www.(.+) [OR,NC]    # Added
    RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
    RewriteRule ^/?(.*) https://domainname.com%{REQUEST_URI} [L,R=301]
</VirtualHost>

为什么它在我的设置中不起作用?

编辑:

<If "req('X-Forwarded-Proto') != 'https'>
    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} !^ELB-HealthChecker
    RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
</If>

我为使用 apache 的 HTTPS 所做的是通过 container commands 上传自定义 redirect.conf 文件。所以 redirect.conf 看起来像这样:

<If "req('X-Forwarded-Proto') != 'https'>
    RewriteEngine On
    RewriteRule . https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
</If>

然后您将使用容器命令将此文件放入 apache 配置目录 /etc/httpd/conf.d/,如下所示:

container_commands:
  01_update_rewrite_rules:
    command: "cp rewrite.conf /etc/httpd/conf.d/"

我已经解决了这个问题很长时间了,现在可以让它成功运行了。我喜欢分享我所做的如下。

(1)Create .htaccess file inside the folder same as root file index.php exists
(2).htaccess file has
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
(3)Then enable mod_rewrite, try the command line command: 
   sudo a2enmod rewrite
(4)To make sure mod_rewrite is enabled, update /etc/apache2/apache2.conf file as
<Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>
initially is 
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

Then you can setup http to https successfully
You need to restart server as sudo service apache2 restart after update of /etc/apache2/apache2.conf 

您的负载均衡器及其安全组需要开放 http 访问。