Redirect http to https codeigniter behind AWS ELB

I have scenario i want to redirect http urls to https from .htaccess CodeIgniter.

Website was hosted on EC2 AWS and behind ELB, this will also works with Cloudflare.But unfortunately after trying several methods my website was showing me error Too Many Redirects

Solution

I found that the load balancer forwards headers like X-Forwarded-Proto. This can be used to determine if the client is using HTTP or HTTPS like so:

# Force to redirect HTTP to HTTPS
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I hope the above helps someone else when trying to force redirect http to https behind AWS Load balancer.

Getting wrong IP with Cloudflare DNS?

If you are using cloudflare then this is for sure you are getting wrong IP address in PHP $_SERVER['REMOTE_ADDR']

Solution for this issue is use X-Forwarder to upload remote_addr

if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
   $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
} 

Looking for more help?

If you still having issue please feel free to ask me in comments below
Soon i will elaborate this article little more for different scenarios.

You May Also Like