Helping Geeks Win the War on Technology Since 2010

Easy Country-Based Redirect in Javascript

March 7, 2012

country based geoip redirect

Previously, I posted about using the Maxmind database to personalize a website to the location of a web visitor. Today I’m going to show you how to further utilize the Maxmind geoip script to perform country-based redirect in super-easy Javascript.

Maxmind, for the uninitiated, is a company that keeps track of location information based off an IP address. So if you were to pass your IP address to Maxmind’s database, they would be able to tell you what city you were surfing from, the state, country, and even longitude/latitude coordinates. There’s no voodoo to it, simply a one-line Javascript include in your HTML file. After including it you are free to use a variety of useful location variables. This example makes use of the country code.

Redirecting a web visitor based on his or her country is a great way to show localized versions of your website if you have special languages that you wish to display. You can also use it to show the most relevant content to your visitor as well. For example, if you had a page with US currency and then had a visitor from the UK, you could convert everything to pounds sterling for a friendlier user experience. Country-based redirection is also great for serving relevant advertisements and localized business offers. The possibilities are endless.

To do it you need to have an entry point page where all your visitors go before getting redirected to the country-based page. The Javascript below can be added between the <head> tags in your HTML.

<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>

<script language="JavaScript">
var country= geoip_country_code();

if(country == "US") {
  window.location = "http://geekhelpguide.com/us/";
} else if(country == "CA") {
  window.location = "http://geekhelpguide.com/ca/";
} else if(country == "UK") {
  window.location = "http://geekhelpguide.com/uk/";
} else {
  window.location = "http://geekhelpguide.com/";
}
</script>

The first line is simply used to include the geoip script from Maxmind. Since Javascript is completely client-side, Maxmind can pull the IP from the visitor and then do a look up for country information. The country code uses the standard two-letter abbreviation which is available here for your reference.

posted in Javascript by helpgeek

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
Powered by Wordpress and MySQL on MDDHosting. Theme by Shlomi Noach, openark.org