Wednesday, September 15, 2010

PHP Redirect Visitors to Another Domain or Subdomain Based on Country

Redirecting visitors to a different domain based on the country of origin is one way to consolidate language translations. For example, I have a site at asdfg.com, and I want Australian visitors to be redirected to asdfg.com.au and UK visitors to be redirected to asdfg.co.uk , I can easily do that with a little PHP and a module called GeoIP. Here are the steps:

  1. Download geoip.inc (PHP API) and GeoIP.dat (GeoLite Country Database) from MaxMind.com.

  2. Create a new folder on our webroot (we will name ours "geoip") and upload geoip.inc and GeoIP.dat into that folder.

  3. Add this code at the top of your index.php file, or any other page that needs to redirect to another domain:

    require_once("/geoip/geoip.inc");
    $gi = geoip_open("/geoip/GeoIP.dat",GEOIP_STANDARD);
    $country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
    geoip_close($gi);

    if($country_code == 'AU'){
    header('Location: http://asdfg.com.au');
    }
    elseif($country_code == 'GB'){
    header('Location: http://asdfg.co.uk');
    }


  4. Save and upload the index.php to your webroot.

  5. To test, you can use an Australian or UK proxy to access your site, and it should redirect accordingly.


I was also able to use this into a Drupal website and it works well - I added the codes into the index.php file. You can also redirect users to subdomains. Let me know if this works for you or not.

1 comment: