• LET'S TALK!

    Fill in the form below to make an enquiry or find my contact details on my contact page.

  • This field is for validation purposes and should be left unchanged.

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

The code snippet below is a demo in how to redirect users to subsites 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 feel free to share and comment :). Do you have a code snippet and you want to see it published on my site? I will be more than happy to do it please send me a message, (here)

ABOUT AUTHOR

Nuno

Hi, I'm a Freelance Web Developer and WordPress Expert based in London with a wealth of website development and support experience. I am great at problem solving and developing quick solutions.

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

  1. Diego says:

    Hello there, I got:

    Don’t Panic
    The code snippet you are trying to save produced a fatal error on line 5:

    syntax error, unexpected token “&”, expecting “]”
    The previous version of the snippet is unchanged, and the rest of this site should be functioning normally as before.

    Please use the back button in your browser to return to the previous page and try to fix the code error. If you prefer, you can close this page and discard the changes you just made. No changes will be made to this site.


    Some update for this snippet?
    Thank you.-

    1. Hi there, code amended. Try again.

Leave a Reply

Your email address will not be published.

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