How to redirect user to other location in according to the country he came from (by IP address)

   —   
This article describes how to redirect user to other location in according to the country he came from (recognized by his IP address).

You can add code for redirection into Application_BeginRequest method in ~\App_Code\Global.asax.cs file (e.g. right before "switch (URLRewriter.RewriteUrl())" line). Please find sample code bellow:

        string ipAddress = HttpContext.Current.Request.UserHostAddress;
        IP2CountryHelper myCountryHelper = new IP2CountryHelper();
        string currentCountryName = myCountryHelper.GetCountryByIp(ipAddress);
        string currentDomain = CMS.GlobalHelper.UrlHelper.GetCurrentDomain().ToLower();

        switch (currentCountryName)
        {
            case "UNITED KINGDOM":
                if (currentDomain != "www.mysite.co.uk")
                {
                    Response.Redirect("http://www.mysite.co.uk");
                }
                break;
            case "AUSTRALIA":
                if (currentDomain != "www.mysite.com.au")
                {
                    Response.Redirect("http://www.mysite.com.au");
                }
                break;
            case "CZECH REPUBLIC":
                if (currentDomain != "www.mysite.cz")
                {
                    Response.Redirect("http://www.mysite.cz");
                }
                break;
            //...
        }

 

You can find appropriate names of countries in ~\App_Data\CMSModules\WebAnalytics\IP2Country\ip2country.dat file - you just need to rename this file to .zip and extract and view ip-to-country.csv file included.

 



Applies to: Kentico CMS 4.0
Share this article on   LinkedIn