Website redirect based on location

imagesWebsite redirect based on location scenario :

  • You have many websites targeting for different user countries. For example: vn.domain.com for Vietnamese users, us.domain.com for US users.
  • You want to allow your users to browse your website as fast as possible, and you have 1 server in Vietnam, 1 server in US, 1 server in UK. These servers are setup for daily synchronization. Then how to load according servers based on user location?

Solutions:

  1. Use PHP (or whatever web programming scripts) to detect IP and do redirection. Can use some free IP2Location DB in the net, such as http://www.ip2location.com OR GeoLite at MaxMin. Problem: This must load the web application tier, and users might experience a delay. To do this:
    • Download MaxMind’s GeoIP.dat database  Free Version (GeoLiteCountry), then download geoip.inc. Upload those two files to the same directory where your page is located.
    • Do redirection in the PHP script as follows
      <?php
      require_once('geoip.inc');
      
      $gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
      $country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
      geoip_close($gi);
      
      $my_countries = array('us', 'gb', 'vn');
      if (!in_array(strtolower($country), $my_countries))
      {
      header('Location: http://www."ALL"TRAFFICURLGOESHERE.whatever');
      }
      else
      {
      header('Location: http://www."SELECTEDCOUNTRIES"URLGOESHERE.whatever');
      }
      ?>
    • Country code can be found at http://www.maxmind.com/en/iso3166
  2. Implement a location-based redirection on web server, so the web application does not need to be loaded. Can use Apache webserver with mod_geoip2 Apache module.
    • More configuration tutorial can be found at the above page.
    • We can also use it in .htaccess file as follows
      GeoIPEnable On
      GeoIPDBFile /path/to/GeoIP.dat
      
      # Start Redirecting countries
      
      # USA
      RewriteEngine on
      RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^US$
      RewriteRule ^(.*)$ http://us.domain.com$1 [L]
      
      # UK
      RewriteEngine on
      RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^GB$
      RewriteRule ^(.*)$ http://uk.domain.com$1 [L]

Leave a comment

Your email address will not be published. Required fields are marked *