How to redirect users to sub sites based on their country IP location using CloudFlare API

 In All, Redirects

The code snippet below is a demo in how to redirect users to sub sites based on their country IP location.
On this code I am using CloudFlare geo location API – the code is not perfect but could be a good starting point 🙂


// collect the current state from the URL and CloudFlare

$user_country_code = strtolower($_SERVER["HTTP_CF_IPCOUNTRY"]);
$site_subdomain = strtolower(array_shift(explode(".",$_SERVER['HTTP_HOST'])));

if ( $user_country_code == $site_subdomain ) {

  // this is already using the country-code mapped version
  // do nothing
  
  } else {

    switch($user_country_code) {  // check if it's a country we currently support

       case 'et';
       case 'us';
       case 'gb'; 
       
       // yes - redirect to the specific subdomain
       header( 'Location: http://'.$user_country_code.'.example.com');
       break;
       default;
       
       // no - redirect to www if not already there
       if ( 'www' == $site_subdomain ) {
         // already at www!
         // do nothing
       
       } else {
       
         // redirect to www
         header( 'Location: http://www.example.com');
         break;
       }
    } 
       
}

Thank you for seeing my code snippet and fell free to share and comment 🙂 . Do you have a code snippet and you want to see it publish on my site ? I will be more than happy to do it please send me a message (here)

Recent Posts

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Start typing and press Enter to search

Let's work together

I'd love to work with you! Please fill out my project form to tell me more about your project/work. I reply to all enquiries within 48 hours.

Availability

  • November - Booked
  • December - Booked
  • January - Available

Rates

  • My day rate is £300.
  • I can provide a fixed price for your work.

EN - Header Enquiry Form

  • This form collects your name, email address and telephone number so that I can respond to the enquiry(ies) that you submit via this website. Please check my privacy policy for the full story on how I use, protect and manage your submitted data.