0

Secure WordPress – Limit Logins to Specified Countries with CloudFlare

Posted (Updated ) in PHP

As I’m sure is the case with just about every WordPress user, my site is constantly hit with failed login attempts from bots – usually originating from other countries. I had the idea last night to implement country-based login restrictions using CloudFlare’s IP Geolocation server variable.

My goal was to redirect redirect all users visiting the login page from countries other than Australia to the home page. This occurs before a login attempt can even be made.

Here’s how it’s done:

  • Go into CloudFlare settings and make sure the IP Geolocation option is turned onMake sure CloudFlare IP Geolocation is turned on
  • Add the following to your active themes functions.php file
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    // Limit login countries - requires cloudflare
    add_filter( 'authenticate', 'login_failed', 1, 3);
    function login_failed( $user, $username, $password )
    {
        if ( !isset( $_SERVER['HTTP_CF_IPCOUNTRY'] ) )
            return $user;
     
        if ( !in_array( $_SERVER['HTTP_CF_IPCOUNTRY'], array('AU') ) )    {
            wp_redirect( home_url() );
            exit;
        }
     
        return $user;
    }

To test simply use a country other than your own. Once it’s confirmed working switch to your country and you’re good to go!