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
?
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;
}
}
Use the following rule:
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With