Disable Web Requests for WP-CLI Only WordPress

Did you know you can use WordPress exclusively from WP-CLI? The use case for doing this is pretty unique. Not likely something you’ll see in the wild. Generally you want WordPress to handle web requests however for a WP-CLI only WordPress site we’ll want to disable them. Let’s look at how we can lock it down so that all web requests are ignored completely.

Randomize home and siteurl is a good start.

With WP-CLI this can accomplished like this.

random=$( php -r 'echo bin2hex(openssl_random_pseudo_bytes( 4 ));' )
wp option set home https://$random
wp option set siteurl https://$random

However if the host name is known then the website could still be accessed by passing the host name with in the web request itself to the server’s public IP.

Prevent web requests within wp-config.php 🔒

The following can be added to the wp-config.php right before the ending part /** Absolute path to the WordPress directory. */.

if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
	echo "<html>Web requests disabled.</html>";
	exit;
}

This method simply checks if the request came from WP-CLI. If not it bails and prevents loading WordPress entirely. For extra protection I’d recommend configuring the server so that that web ports 80 and 443 are inaccessible.