Cloudflare Logo

Use CloudFlare to Secure WordPress by Country Codes

Firstly, check that you have the IP Geolocation option enabled on CloudFlare.

The most efficient way to do this with PHP would be to place the code below in the top of your wp-login.php, but WordPress will overwrite this file when it updates. The next best position is at the top of wp-config.php. If you follow the way WordPress loads, wp-login.php will require wp-load.php first, then after 4 minor lines of code, it will then get wp-config.php.

/**
 * CloudFlare - Connecting IP - for wp-config.php.
 */
if ( !empty( $_SERVER['REMOTE_ADDR'] ) && !empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) )
    $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];

/**
 * CloudFlare - Limit WordPress Login to Australia with Whitelist - for wp-config.php.
 * It is best to bypass for IPv6 unfortunately, unreliable country code from CloudFlare at the moment.
 */
$ip_whitelist = array( '::1', '127.0.0.1' );

if ( in_array( $_SERVER['PHP_SELF'], array( '/wp-login.php' ) ) && !in_array( $_SERVER['HTTP_CF_IPCOUNTRY'], array( 'AU' ) ) )
{
    if ( !in_array( $_SERVER['REMOTE_ADDR'], $ip_whitelist ) && !preg_match( '/^([0-9a-f\.\/:]+)$/', $_SERVER['REMOTE_ADDR'] ) )
    {
        header( 'Location: /' );
        exit;
    }
}

This is just a different interpretation of my friends script. My version does not allow WordPress to waste CPU before booting the IP from the login page. It also allows for an IP whitelist to bypass this for trusted IP addresses.

It is best to pair this with a plugin like Simple Login Lockdown. There are also some useful .htaccess rules you can use, but I won’t go into that here.