Website redirect based on location

imagesWebsite redirect based on location scenario :

  • You have many websites targeting for different user countries. For example: for Vietnamese users, 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?


  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 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 Upload those two files to the same directory where your page is located.
    • Do redirection in the PHP script as follows
      $gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
      $country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
      $my_countries = array('us', 'gb', 'vn');
      if (!in_array(strtolower($country), $my_countries))
      header('Location: http://www."ALL"TRAFFICURLGOESHERE.whatever');
      header('Location: http://www."SELECTEDCOUNTRIES"URLGOESHERE.whatever');
    • Country code can be found at
  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 ^(.*)$$1 [L]
      # UK
      RewriteEngine on
      RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^GB$
      RewriteRule ^(.*)$$1 [L]

About NhocConan

A super lazy guy who tries to write tech blog entries in English.He is lazy, so he can only write when he is in a good mood or when he is tired of coding.

Leave a comment

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