Redirecting http to https in Google Cloud

自作多情 提交于 2020-01-01 05:42:08

问题


I have setup a load balancer which accepts https connections from users. The compute engines are then connected to load balancer using http connection.

I have written the following .htaccess file in the root folder:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Now, the problem is, the compute engine is always connected via http link (to the load balancer) and not https.

Thus, the .htaccess file always consider the connection to be http and not https even if the url starts with https. So, it goes in an infinite loop trying to send the user to https even when the url is https.

What should be done to redirect http to https in this case.

Thanks.


回答1:


You should check the X-Forwarded-Proto http header. It is set by the load balancer and will have the value http or https.




回答2:


This took so long for me to find the answer to! Thank you so much @Lennert!


    user@host-vm:/opt/bitnami/apps/wordpress/htdocs# head -4 /opt/bitnami/apps/wordpress/conf/htaccess.conf 

    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteRule . https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]




回答3:


For those who are using php, I've been looking for a simple way to make my project redirect any page to https in Google Cloud, and I found a simple solution. All you have to do is to add this code at the top of your php page. It has to be at the top, the F̲i̲r̲s̲t̲ L̲i̲n̲e̲ of code in your header:

<?php
if ($_SERVER['HTTPS'] == 'off') {
  header("Location: https://www.YOUR_SITE.com".$_SERVER['REQUEST_URI']);
  die();
}
?>


来源:https://stackoverflow.com/questions/38201969/redirecting-http-to-https-in-google-cloud

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!