WordPress Infinite Redirection Loop

One thing we often have to do as web developers, is update the main URL of the site. Usually, it’s because we need to configure the site on a new server. This might be becase you’re migrating to a new hosting company, or just creating a new environment at your current web host.

Privacy is becoming more important, especially on the web. Recently it’s become easier to secure your site by getting a SSL certificate, thanks to the Let’s Encrypt project. They’ve made it easy and free to create an SSL certificate. If you haven’t switched your site to SSL, make that your next project.

Updating your Site URL in WordPress

In WordPress, it’s easy to update the URL. In the admin dashboard, under Settings > General, you update the WordPress Address (URL) and Site Address (URL). While this is the easy way, when your site is redirection, the admin dashboard will be inaccessible. There are two other ways to update those values – update the database via SQL queries, and executing commands via WP-CLI.

Sometimes WP-CLI isn’t available, so I chose to use SQL. In the wp_options table, you should check the current values of the ‘siteurl’ and ‘home’ options with the following query:

SELECT option_name, option_value
FROM wp_options
WHERE option_name IN ('siteurl', 'home');

This one changes the value of the ‘siteurl’ and ‘home’ options.

UPDATE wp_options
SET option_value = 'https://example.com'
WHERE option_name IN ('siteurl', 'home');

Infinite Redirection Loop

Normally changing those values are enough. For most sites, that’s the case. So how does the rediretion loop happen. Well, we have an addition piece of tech in the mix – a load balancer. This is used to simplify the managaement of the security certificates. You may be wondering, how? Instead of putting the certificates on each web server, you install them on the load balancer. This reduces the number of SSL certs you need to install. It saves on a fair amount of work.

The load balancer is a type of reverse proxy. It’s job is to forward (send) requests to one from a pool of servers. When a request is sent via https, the load balancer adds this header HTTP_X_FORWARDED_PROTO to the request before sending it to the server.

WordPress has an is_ssl() function, that gets called when is creates URLs. The site_url() and home_url() functions both use the is_ssl function. So any theme file calling either of those functions, will trigger the loop.

Solution

The is_ssl() function looks for a $_SERVER setting named HTTPS, to determine the presence of a secure connection. To help WordPress, use the following snippet in your wp-config.php file.

if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) {
    $_SERVER['HTTPS']='on';
}

This addition will cease the loop of redirection, and WordPress will go back to serving your pages normally. I hope that helps.

Sorry, but comments are closed. I hope you enjoyed the article