Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force HTTP to HTTPS through an AWS EC2 load-balancer

We have an AWS EC2 load-balancer and it has SSL certificate installed on it. But the servers in the pool are still running on port 80 and non-SSL protocol.

The issue is that i do not have access to the load-balancer, but i still have to route the non-SSL traffic to secure HTTPS. I tried adding following in the htaccess but it did not work and understandable that is because the servers are still running on HTTP.

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I tried the same thing in PHP code, that did not work either.

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") {
        $url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        redirect($url);
        exit;
    }

So, i get that servers are still running on HTTP and the certificate is only applied on load-balancer. What would be the best solution to forc such redirect in this scenario. One solution i could think of is parsing URL in the code to see if it has http:// in there and redirect. This might work but i dont really think it as a clean and final solution. Is there a way AWS EC2 can redirect in such manner? I am not familiar with AWS EC2.

Also, are there any server parameters that might suggest that the server is running on port 80 but the HTTPS is still on?

like image 476
xmaestro Avatar asked Mar 15 '23 00:03

xmaestro


2 Answers

I was able to find a solution in AWS docs here.

It says that AWS load-balancer forwards following server vars to the pool.

X-Forwarded-Proto specifies the protocol (“http” or “https”) of the original request made to the Elastic Load Balancer.
X-Forwarded-Port specifies the port of the original request.

So, since we are using AWS EC2, it solves the problem but be careful using in case you are using some other environment since they might not be present there.

The complete code is:

if(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])){

        if ($_SERVER['HTTP_X_FORWARDED_PROTO']=="http") {
            $url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
            redirect($url);
            exit;
        }

    }
like image 146
xmaestro Avatar answered Mar 23 '23 08:03

xmaestro


Use the following rule:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
like image 27
Ravi Shanker Avatar answered Mar 23 '23 08:03

Ravi Shanker