WordPress: Fixing the “Too many redirects” error when using HTTPS and .htaccess

So you’ve installed your SSL certificate, and updated your WordPress settings to make the switch to HTTPS…

So far, so good…

…only to find your site is still accessible by HTTP!

So you try implementing a .htaccess redirect…

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

…only to get hit with “Too many redirects” errors in the browser.

The good news is – it’s easy to fix!

First – remove any attempts to enforce SSL from your your .htaccess file (such as the above example).

Second – add this to the wp_config.php file in your root directory, just before the /* That's all, stop editing! Happy blogging. */ comment:

if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
    $redirect = 'https://www.YOURDOMAIN.com' . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}

I’ll be honest, I’m not entirely sure why certain webhosts exhibit this behaviour – but implementing the redirect in PHP rather than .htaccess has worked in a handful of instances, so hopefully it can help you too.