Fix Undefined index: HTTP_X_FORWARDED_PROTO with WP-CLI


Are you running your WordPress install behind an SSL proxy or load balancer like HAProxy? You may also be running WP-CLI on the internal site.

To get SSL to pass-through correctly a lot of sites have outlined that you need to add the following code to your wp-config.php

define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')

Although this is almost correct, the HTTP_X_FORWARDED_PROTO line is incorrect. If you use this code your WordPress site will work correctly with your SSL certificate on your proxy/load balancer. But if you try and run a WP-CLI command you’ll get the following error.

PHP Notice:  Undefined index: HTTP_X_FORWARDED_PROTO in phar:///usr/local/bin/wp/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(1197) : eval()'d code on line 71

After some searching, I found this closed issue in the WP-CLI GitHub issues. It has a reply from Daniel Bachhuber the previous WP-CLI maintainer with an easy fix.

The Fix

The fix is pretty straight forward and all you have to do is check that the index exists and then set it as required. Updated your wp-config.php file to look like this.

define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'){ $_SERVER['HTTPS']='on'; }

Once you have added the array key check it’ll work correctly both for the site itself and for wp-cli.