How to fix the infinite redirect loop when using CloudFlare Flexible SSL

24 November 2016 • in Tips

A few weeks ago I made the switch to SSL using CloudFlare free Flexible SSL. I activated the feature on CloudFlare and updated my WordPress site address accordingly.

I visited the homepage and I was welcomed by an infinite redirect loop error :

Error code: ERR_TOO_MANY_REDIRECTS

WordPress has its very own is_ssl() function to check if you are visiting the website through SSL or not. It uses $_SERVER['HTTPS'] and $_SERVER['SERVER_PORT'] PHP superglobals to check if the page is being accessed over SSL or not. It should be fine but CloudFlare Flexible SSL is an exception among others.

CloudFlare acts as a proxy between your site and your visitor. When using Flexible SSL, CloudFlare handles all your traffic over SSL and redirect it to your website over HTTP using the port 80. It messes with WordPress way of handling SSL requests.

infinite-redirect-loop-cloudflare-flexible-ssl

Don’t worry, it’s easy to fix. CloudFlare kindly provides an HTTP header flag that says : “Hey, I am using SSL for this request!”. Next step is to tell PHP that we are using SSL by adding those lines to the beginning of the htaccess :

<IfModule mod_setenvif.c>
SetEnvIf X-Forwarded-Proto "^https$" HTTPS
</IfModule>

It will set the HTTPS environment variable to 1 if the X-Forwarded-Proto contains https. PHP will handle it and update the $_SERVER['HTTPS'] superglobal accordingly.

Your WordPress website should now be handling SSL requests without any hassle.