0

我在here之前已經提出了查詢。我認爲它正在工作,但實際上還沒有。使用AWS的ELB從Http重定向到https https

我有面向Internet的負載均衡器,後面是Ec2實例。 我的負載均衡器打開端口80和443

他們被安排爲80 - > 80和443 - > 80

現在是我需要重定向到https HTTP訪問。

我所做的是 我製作了一個.htaccess文件並位於/ var/www/html /中。這是我的網站的index.php所在的文件夾。

在.htaccess文件裏面,我嘗試了幾個我在互聯網上找到的版本。他們都沒有工作。

<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> 
+0

我從AWS獲得了一條線索的回覆,那就是ELB只是使用X-Forwarded-Proto插入重定向信息。所以實際的重定向實現需要在實例中發生,在Apache中。我需要弄清楚如何。 – batuman

+0

Phabricator解決了類似的問題。 https://stackoverflow.com/a/48149369/7098257 –

回答

0

我一直在解決這個問題的很長一段時間,現在可以使它成功地工作。我喜歡分享我所做的如下。

(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訪問。

0

我爲HTTPS做什麼用Apache是​​通過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/" 
+0

你的意思是把這個放在/ etc/httpd文件夾裏面並且裏面有conf.d文件。我無法找到/ etc/httpd文件夾。與conf.d相同 – batuman

+0

您正在使用哪種AMI? '/ etc/httpd/conf.d /'是linux上的默認apache配置目錄 – chukkwagon

+0

我使用Ubuntu 16.06 – batuman