Redirect loop when site sits behind a proxy service such as Cloudfront or Cloudflare

Solve an endless redirect loop, experienced when your WordPress website sits behind a proxy service such as Cloudflare or Cloudfront


If your WordPress website sits behind a proxy service such as Cloudfront or Cloudflare and is served over HTTPS, you may experience a redirect loop that prevents the site from being accessed:

This typically happens when you have the URL of your website, as set in the wp_options table via the siteurl and home options, set to an https:// URL. This redirect loop occurs because the server-side code does not recognise the site as being accessed over HTTPS and so endlessly tries to redirect you to a secure version until the browser gives up. If you set the site URL to use the http:// prefix you may find that the site is accessible, however the site will not be fully secure as asset URLs such as CSS, JS and image files will all be loaded over http:// rather than https://.

The reason that the HTTPS protocol you’re accessing the website over is not recognised is due to the proxy service that sits between your browser and the website. Your browser may be connecting to the Cloudfront or Cloudflare equivalent service over HTTPS but when the server receives the connection from the proxy, it is unaware of the secure connection being made on the frontend.

To resolve this, we need to make use of the HTTP_X_FORWARDED_PROTO header that is passed in the request from the proxy service to the web server that indicates the browser is accessing the site over the HTTPS protocol. The following code, added to your wp-config.php file, will set the HTTPS header to a value of ‘on’ when this HTTP_X_FORWARDED_PROTO header is set to ‘https’:

/**
 *  Enable HTTPS behind proxy service
 */

if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
    $_SERVER['HTTPS'] = 'on';
}

With this code in place, you should see the redirect loop is resolved and the site becomes fully accessible over HTTPS.

A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones