How to solve the endless redirect loop issue when using WordPress on a SSL secured sitePosted on 2015-11-24

Recently I ran into a fiddly problem and I like to share my solution. After moving a SSL secured WordPress site from one hoster to another all pages loaded without any styling and trying to access the admin dashboard ended in an “There where too many redirects” error.

The first thing I’ve tried was to deactivate all plugins by renaming the plugins folder. No success. Afterwards I completely deleted WordPress  and the database and uploaded a fresh WordPress copy. After finishing the installation the problem still existed.

Analyzing the HTTP traffic I found out that when trying to access the wp-admin the browser was redirected to the same URL again and again and again… As it was a freshly installed WordPress without any plugins there must be a problem with SSL. To verify my assumption I made a quick change to the WordPress core. This solved the problem – but of course this is not a suitable solution.

After some research I found out that this is a known issue that occurs when a website is hosted behind a load balancer. The WordPress check whether a page is loaded with the HTTPS protocol is based on a couple of clues – but those aren’t always available behind a load balancer.

That fact is mentioned in WordPress Codex. But you have to know what to look for… Searching the WordPress Trac shows that over the years there have been several requests to change the way WordPress checks if SSL is used. But the WordPress Core Development Team decided not to fix this because in their opinion this is not a core issue.

It’s a big problem – but the soultion is very simple. You just have to manipulate a server variable that WordPress uses to check for SSL to get the proper result. This requires just one line of code. To prevent this change from being overwritten by the next WordPress update just put it into the wp-config.php file. This config file never is touched by updates.

The best place for adding the required code is right before the line
/* That's all, stop editing! Happy blogging. */

And that’s the code to add:
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') $_SERVER['HTTPS'] = 'on';

In my case this solved the problem. But this solution requires a load balancer that supports HTTP_X_FORWARDED_PROTO. If this solution does not work for you try the following code:
if (stripos(get_option('siteurl'), 'https://') === 0) $_SERVER['HTTPS'] = 'on';

Great events often come from little causes!

Short URL to this page: http://p12.click/433Pg