How can I redirect traffic based on the visitor's country?

34 replies
How can I redirect traffic based on the visitor's country? The title is quite self-explanatory.
What I want to do is redirect traffic from certain countries to another web page.

More specifically, what I want to do is redirect all the traffic to a web page "X", EXCEPT traffic coming from countries ("A" | "B" | "C"), that will be redirected to another web page "Y".

I've found some possible solutions, such as MaxMind's API: GeoIPCountry (GeoLiteCountry):
MaxMind - GeoIP Apache API

But, I'm a member of BlueHost and they do not support mod_geoip

I'm not sure if that is 100% necessary to make it work, since there are other API's available too (PHP, etc.)

Is there any other way to successfully do this?

Does anyone know where I can get step-by-step instructions on how to do this? I don't really know anything about coding/scripting

Any help would be appreciated. Finding a solution to this is really important for me right now!

Thanks in advance,
Pablo
#based #country #redirect #traffic #visitor
  • Profile picture of the author PabloVTB
    Ok, I've been searching a lot and I have found this possible solutions. Both use PHP and GeoLiteCountry data to function:

    1) Source: Site 2nd Geoip-php script to redirect user based on country

    I got problem to install mod_geoip in my server. So I use the most simple method to redirect users. I just use a php script to do it. Here is a script to redirect user based on their countries by using geoip.dat.
    [sourcecode language='php']
    /**
    * Case Study - GeoIP Redirection
    *
    * @version $Id$
    * @package geoip
    * @copyright © 2006 Lampix.net
    * @author Dragan Dinic
    */
    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 == 'CS')
    {
    header("HTTP/1.1 301 Moved Permanently");
    header('Location: http://www.example.net/1/');
    }
    else
    {
    header("HTTP/1.1 301 Moved Permanently");
    header('Location: http://www.example.net/2/');
    }
    ?>
    [/sourcecode]
    Change the geoip/geoip.inc and geoip/GeoIP.dat path accordingly.
    Change if($country_code == 'CS') to your desire country code.
    Change header('Location: http://www.example.net/1/'); to your desire URL.
    That's it! Easy!

    2) Source: How-to use maxMind GeoIP for websites | PHP Forums

    Sometimes you need to redirect visitors based on the country they come from. Maxmind provides a great country/IP address database in binary format. The following example will show you how redirect visitors from countries which are not on the "whitelist".

    Download the latest Geo data and the class file here


    Copy the class file and the GeoIP data file into the same directory where the page is located (most of the time the root directory)


    Include the class file inside your page and add the following code to request the country using the following code (below the include statements):

    $gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
    $country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
    geoip_close($gi);

    Define some country codes the "whitelist":

    $my_countries = array('us', 'ca', 'gb', 'fr', 'de', 'nl');

    Next place the following code below the $mycountries array:

    if (!in_array(strtolower($country), $my_countries)) {
    header('Location: some URL...');
    exit;
    }



    =========================================
    =========================================

    Guys! I did it!


    Ok, so, just to let you know, this is how I did it:

    I don't really have ANY experience with PHP, but I started searching everywhere to find a solution. And this seems to have worked:

    First, I downloaded MaxMind's GeoIP.dat database from here:

    http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
    Free Version (GeoLiteCountry)

    Then I downloaded geoip.inc from here:
    http://geolite.maxmind.com/download/.../php/geoip.inc

    Then I uploaded those two files to the same directory where my page is located.

    I edited my php page and wrote this script inside of it:

    Code:
    <?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', 'ca', 'gb', 'fr', 'de', 'nl');
    if (!in_array(strtolower($country), $my_countries))
    {
    header('Location: http://www."ALL"TRAFFICURLGOESHERE.whatever');
    }
    else
    {
    header('Location: http://www."SELECTEDCOUNTRIES"URLGOESHERE.whatever');
    }
    ?>
    Simply change the country codes you want to target in the line:

    $my_countries = array('us', 'ca', 'gb', 'fr', 'de', 'nl');

    and the URLs for both the targeted traffic and rest traffic where mentioned.

    Country Codes can be found here: MaxMind - ISO 3166 Country Codes

    Woalah!
    Hope this helps!
    {{ DiscussionBoard.errors[692951].message }}
    • Profile picture of the author jskarthik1
      Hey PabloVTB!!! that's awesome.. thanks a lot!
      {{ DiscussionBoard.errors[6897447].message }}
  • Profile picture of the author khtm
    I just setup the MaxMind free geo redirect script too - works great!

    I'm using it to redirect visitors to either Amazon US, Canada, UK, Germany, France, or China.
    {{ DiscussionBoard.errors[830711].message }}
    • Profile picture of the author Barnsy
      Originally Posted by khtm View Post

      I just setup the MaxMind free geo redirect script too - works great!

      I'm using it to redirect visitors to either Amazon US, Canada, UK, Germany, France, or China.
      Did you have to set up multiple associate accounts with Amazon for this?

      (Sorry to thread-jack)
      {{ DiscussionBoard.errors[836018].message }}
      • Profile picture of the author jjblack
        Hi guys,

        This is exactly what I want... however it doesn't seem to work.

        I have uploaded the two files to my site - GeoIP.dat, geoip.inc

        I have then added the script to my page...

        Now.. does it have to be a PHP file? can it be within a html page? Where does it go? in the <head> section in script tags or the <body> section or what?

        It's just not working... can someone help?

        Thanks
        {{ DiscussionBoard.errors[2116794].message }}
        • Profile picture of the author ankit_frenz
          Originally Posted by jjblack View Post

          Hi guys,

          This is exactly what I want... however it doesn't seem to work.

          I have uploaded the two files to my site - GeoIP.dat, geoip.inc

          I have then added the script to my page...

          Now.. does it have to be a PHP file? can it be within a html page? Where does it go? in the <head> section in script tags or the <body> section or what?

          It's just not working... can someone help?

          Thanks
          Must be php..scripts dont work in html..put it on top of the page before html starts
          {{ DiscussionBoard.errors[2424603].message }}
        • Profile picture of the author Snatch
          Originally Posted by jjblack View Post

          Hi guys,

          This is exactly what I want... however it doesn't seem to work.

          I have uploaded the two files to my site - GeoIP.dat, geoip.inc

          I have then added the script to my page...

          Now.. does it have to be a PHP file? can it be within a html page? Where does it go? in the <head> section in script tags or the <body> section or what?

          It's just not working... can someone help?

          Thanks
          I have the same question...anybody????..........................
          {{ DiscussionBoard.errors[4797243].message }}
  • Profile picture of the author bestofcuba
    Anybody have experience with blackhat codebreaker and geolite geoip? I'm trying to implement geoip capability to the bhcb script. Have a problem in the .htaccess rewrite (links.txt -> links.php). It displays the proper links from each country, but still links to the original links.txt instead of using the rewrite links.php country links.
    I'm using this concept: Remote Insider Affiliate Marketing Forum - View topic - How to Modify BJ Codebreaker

    Any info or suggestions on this??
    {{ DiscussionBoard.errors[2424181].message }}
  • Profile picture of the author Deniro
    Power Redirector seems to be a good redirect script, works with different kind of databases
    {{ DiscussionBoard.errors[3896107].message }}
    • Profile picture of the author andrejvasso
      First of all: Grats to Pablo! Its always a great experience to solve a problem totaly on its own, isnt it?

      A few more thoughts:

      The geomax scripts work fine - however I sometimes encounter little speed problems, but its okay - also I am using the geoip javascript to get visitors info withouth downloading the geoip.dat on my own server and therefor making it a bit slower maybe....

      @bestofcuba: keep up the work! i have done almost the same a few years ago when bhcb was just released - so I know for sure it can be done and its a simple task. Unfortunatelly, I think I have lost the files I will try to look for them and pm you if i found them.

      However, as far as I can remember, there is no need to add .htaccess rules for redirection. You should think about this:

      adding a link to your geo-redirection script inside links.txt -> once a vistors clicks on it -> redirects to geo script -> check country -> redirect to an offer in his country.

      hope this helps and i will keep you updated when i find my old files.
      {{ DiscussionBoard.errors[3896793].message }}
    • Profile picture of the author Vincent1988
      Originally Posted by Deniro View Post

      Power Redirector seems to be a good redirect script, works with different kind of databases
      I too used this one, but got some problems with my server. Do you have a demo?
      {{ DiscussionBoard.errors[3905689].message }}
  • Profile picture of the author twoelevenjay
    I have done everything here however on my godaddy FTP I can not unzip the GeoIP.dat.gz file and If I unzip it on my computer the GeoIP.dat seems blank and when I upload it the PHP script return an error saying the GeoIP.dat does not exist. Can anyone help this is driving me nuts lol
    {{ DiscussionBoard.errors[6532420].message }}
  • Profile picture of the author dgmufasa
    Thanks for this solution I was looking for something like this as well
    {{ DiscussionBoard.errors[6538227].message }}
  • Profile picture of the author seokid
    You should have ip to country database and find ip address using language you are using and then compare with the database and redirect accordingly
    {{ DiscussionBoard.errors[6538563].message }}
  • Profile picture of the author twoelevenjay
    is the .dat file suppose to be uploaded to my mysql data base?
    {{ DiscussionBoard.errors[6543901].message }}
    • Profile picture of the author jiffyspop
      I use max mind and I have purchased the database I use it for my free ad service. There are a few things you have to do with maxmind. One is compile it into the server then your able to use it threw your server PHP: GeoIP Functions - Manual if you cannot install it into your server then you can use the free but its like 40% of ips arent in the data dat file. also you must make a robot.txt file for it so the bots dont crawl threw it because it will corrupt the database. If you purchase it the you can download the new dat file every month. Its 350 plus I think 90 dollars a month.
      {{ DiscussionBoard.errors[6544979].message }}
    • Profile picture of the author jiffyspop
      Originally Posted by twoelevenjay View Post

      is the .dat file suppose to be uploaded to my mysql data base?
      no but the you can upload a directory of all the countries and region staes it is 3 tables and you combine those table with the dat file and you can create a very effective way of tracking users know if you us the browser file Browser.php – Detecting a user’s browser from PHP | Chris Schuld's Blog u can track and redrect to the template of what type of browser. I have done this with many websites and have my own script that does this
      {{ DiscussionBoard.errors[6545007].message }}
      • Profile picture of the author twoelevenjay
        Originally Posted by jiffyspop View Post

        no but the you can upload a directory of all the countries and region staes it is 3 tables and you combine those table with the dat file and you can create a very effective way of tracking users know if you us the browser file Browser.php - Detecting a user's browser from PHP | Chris Schuld's Blog u can track and redrect to the template of what type of browser. I have done this with many websites and have my own script that does this
        I am a little confused by this. The original instructions on this thread is what I was able to follow. But it did not work. It tells me the .dat file that I uploaded is not there. This is something I need done ASAP cuz customers are able to see the different prices we offer different countries. Can you help me with this?
        {{ DiscussionBoard.errors[6545361].message }}
        • Profile picture of the author jiffyspop
          well try to upload the dat file as a zip or rar then extract it. know with asap I do belive your going to want to do this in C or C# then youll be able to do it. It can be a real pain to do in asap. I find that maxmind is easier to do in php. I am on my labtop not on my desktop or I would give what I wrote in C. But if you know C or C# it will be easy.
          {{ DiscussionBoard.errors[6545590].message }}
  • Profile picture of the author ryanroy07
    I currently use the open source wordpress, any method can be applied with wordpress?
    Any help would be appreciated.
    Thanks again.
    {{ DiscussionBoard.errors[6634434].message }}
    • Profile picture of the author annife polak
      Im using WordPress Geo IP Redirect, it not free. But it's only for 5 bucks

      Cheers!
      {{ DiscussionBoard.errors[6635984].message }}
      • Profile picture of the author ryanroy07
        Originally Posted by annife polak View Post

        Im using WordPress Geo IP Redirect, it not free. But it's only for 5 bucks

        Cheers!
        It is the best method for the newbie like me on the issue coder. Add one more question, it can affect the index of the search engines?
        Sincerely.
        {{ DiscussionBoard.errors[6648189].message }}
        • Profile picture of the author Nicheguy
          Hello ryanroy07,
          Can you tell me what plugin you are using and where I can find it. I tried to do a search and it is not coming up!

          Thanks
          Nicheguy
          Originally Posted by ryanroy07 View Post

          It is the best method for the newbie like me on the issue coder. Add one more question, it can affect the index of the search engines?
          Sincerely.
          {{ DiscussionBoard.errors[7397446].message }}
  • Profile picture of the author James Andy
    Well, in the meantime I had it setup with the Geo Direction (bottom of the page) code and changed the country to suit mine.
    {{ DiscussionBoard.errors[6918451].message }}
  • Profile picture of the author whiterock
    If you have ip to country database you can fetch ip address of the visitor using dynamic scripting and you can then redirect using case as per the country found
    {{ DiscussionBoard.errors[6918816].message }}
  • Profile picture of the author SteveSRS
    If you are using cloudflare.com the country short code is automatically available as $_SERVER['HTTP_CF_IPCOUNTRY'] value. Further more it is good for your site speed and also adds another layer of protection

    another alternative to geip is ip2location basically same thing though
    {{ DiscussionBoard.errors[6924301].message }}
  • Profile picture of the author michealburns
    WHAT DOES IT DO?

    - Target Country by IP Address is a complete web-based software that provides webmasters with the ability to redirect/restrict traffic based on the visitor's country of origin.This allows webmasters to promote their services and products in different countries where they have specific distribution and service capabilities in different countries.

    - It features an IP exception list, where you can place your trusted IPs for exceptions.

    - Blocks certain IP address's from your site and redirects the user to a blocked page.Very simple add the IP range or single IP you want to block then.

    - The script should be included in unlimited number of pages on your website so it could redirect visitors to those web pages according to the redirection rules.

    - With this script you can create as many "redirection rules" as you want. On the same website, some pages could have different redirection rules than the others. You could use the same databases and the same script. Only you make a new "redirection rules" , just edit the REDIRECTION RULES file. Then include it in your files.

    - The country code of the visitors is saved in a cookie or a session variable in order to avoid searching the IP database repeatedly.

    - You can specify for each country (or IP database) has a Redirection Rule (a redirection link associated with it). If the visitor`s IP is in an IP database, he is redirected to the redirection link associated with it, or if this one is blank, to the default redirection link.
    If this default redirection link is blank too, the page is loaded. If the visitor`s country has no Redirection Rule specified, he is redirected to the default 'reject' link or if this one is blank, the page is loaded.

    - It is avalable for IP databses: "Plain text - one file with IP numbers and country code", "Plain text - one file with IP addresses and country code", "MySql dump - one table with IP numbers and country code".- all available at http://www.analysespider.com.

    - The free IP2Country database(73% accurate) included in this distribution has only 172
    countrieswith 37879 records. it`s by far not as accurate and updated as our commercial database, available at http://www.analysespider.com

    - It also creates an array with visitor`s country information

    REQUIREMENTS:
    Web server with PHP minimum version 4.1.x, optionaly MySql;

    FILES:
    cr/.htaccess - Apache restriction file, to deny access to cr/ folder, to avoid abuse.
    cr/anp_ips.dat - a free IP2Country database - type: Plain text full with IP numbers
    cr/anp_ip2country.sql - Sql Dump of the same free database
    cr/exceptions_ips.dat - A list of IPs who will be excuded from the redirection. It can only have IP addresses (192.168.0.1) or IP address ranges; Edit this file to add exceptions ip address; Exemple:
    128.177.244.100
    194.112.94.250;194.112.94.255
    cr/blocked_ips.dat - A list of IPs who will be blocked from the redirection. It can only have IP addresses (192.168.0.1) or IP address ranges; Edit this file to add blocked ip address; Exemple:
    213.120.148.65
    213.120.148.70;213.120.148.123
    cr/cr.php - main script file
    cr/anp_****.php - aditional functions
    cr/cur_re_rules.php - default redirection rules file.
    cr/_re_rules.php - redirection rules template file.
    cr/Countries.php - Get Country information files
    cr/Countries.* - Country information files
    cr/flags/* - GIF country flags

    IP NUMBERS AND IP ADDRESSES:
    The unique 4-part number assigned to each and every computer linked to the Internet (e.g., 207.41.2.111). When you connect to the Internet, your ISP assigns you an IP number for the duration of your connection.
    The formula to convert an IP Address of the form A.B.C.D to an IP Number is:
    IP Number = A x (256*256*256) + B x (256*256) + C x 256 + D
    Which is the same as:
    IP Number = A x 16777216 + B x 65536 + C x 256 + D

    INSTALL:
    - Edit cr/cr.php and modify it as described there.
    - Add the next line at the beginning of EVERY PAGE YOU NEED TO REDIRECT VISITORS:

    <?PHP $anp_path="cr/"; include($anp_path."cr.php"); ?>

    or (if cr/ directory is a level up)

    <?PHP $anp_path="../cr/"; include($anp_path."cr.php"); ?>
    - If you use MySql, load cr/anp_ip2country.sql into your mysql server:
    mysql -u [username] -p
    mysql>use [your database]
    mysql>source [path to/]anp_ip2country.sql

    - If you want a different set of redirection rules in other pages of your website,you could use the same databases and the same script. All you can make a copy of _re_rules.php -> new_re_rules.php,edit new_re_rules.php, just change the REDIRECTION RULES. Then include it in your files with:
    <?php $re_rules = "new_re_rules.php"; $anp_path="cr/"; include($anp_path."cr.php"); ?>

    THE IP DATABASE
    - The free IP -> Country database has data for 172 countries and the dat file size is 851 Kb.
    The number of records is 37879 and the number of IP addresses covered is 2,351,067,326 .it`s 73% accurate.
    - You can get an updated and optimized IP database from http://www.analysespider.com with data from RIPE, ARIN, APNIC and LARNIC public databases.
    It has data for 209 countries and the data file size is 3.06 Mb
    At the time when this script was released the number of records was 132,532 and the IP addresses covered were 4,145,812,945.
    Target Country by IP Address was designed for this database and we strongly recommend that you install this one. Used with this script is 98% accurate because of the search functions.


    TESTING AND DEBUG-ING
    To test and debug you need to set in cr/cr.php the constant _DEBUG_MODE to 1: define("_DEBUG_MODE","1") then poin your browser to http://yoursite.com/demo.php. Now play with the configuration, modify redirection rules. When you are satisfied, set _DEBUG_MODE to 2 in order to test how cookies / session vars are saved. When it`s ok set _DEBUG_MODE to 0.


    CONFIGURATION TIPS
    - If you want to use Target Country by IP Address just to detect the country of your visitor and to get the country details in an array, edit cr/cur_re_rules.php comment out all REDIRECTION RULES and make blank the default redirect and reject links ( =""; ).
    Then edit demo.php to see how you can use the country details of your visitor.
    Add the next line:
    <?php include($anp_path."countries.php"); $anp_cinfo=get_cinfo($anp_country_code);?>

    This fields can be used in your scripts: $anp_cinfo["code"] $anp_cinfo["name"] $anp_cinfo["region"] $anp_cinfo["capital"] $anp_cinfo["currency"]
    $anp_cinfo["flag_path"] ; The flag image can be generated like this: <img src="<?php echo $anp_cinfo["flag_path"]; ?>" alt="" border="0">

    - If you want to restrict access to visitors from XX country,Or you want to block a whole lot of countries but make exceptions for some search spider ip addresses.
    You have to add the IP address or the network`s IP range in the cr/exceptions_ips.dat file in order for the visitors to be able to visit your website.

    - Blocks certain IP address's from your site and redirects the user to a blocked page.
    You have to set :
    $bCheckBlocked = true
    $anp_blocked_reject_link= an invalid url.

    Then Edit blocked_ips.dat,add the IP addresses (197.208.0.1) or IP address ranges you want to block. Exemple:
    213.64.128.65
    213.64.108.50;213.64.148.13

    - If you want to use Target Country by IP Address to safely reject all visitors from country XX and YY and to accept all the other visitors
    You must set :
    $anp_default_reject_link="";
    $anp_default_redirect_link="";

    edit the Redirection Rules file(cur_re_rules.php), for country XX uncomment the line and place an invalid url for it (XX=error.php) . Do the same for YY.

    - If you need to display language specific pages for Italy and German:
    You can set :
    $anp_default_reject_link="";
    $anp_default_redirect_link="";

    edit the Redirection Rules file(cur_re_rules.php), for country IT uncomment the line,
    as redirection rule set IT=yourpage_en.htm; Do the same for DE;
    {{ DiscussionBoard.errors[6924724].message }}
  • Profile picture of the author seanpearse
    I'm certainly no expert on the subject and maybe I'm missing something here but wouldn't the hreflang attribute be a much simpler solution? I know it's primarily aimed at directing visitors to pages in different languages but it's the same principal. Isn't it??
    {{ DiscussionBoard.errors[6926760].message }}
  • Profile picture of the author thisisraz65
    thanks great tips and working
    Signature
    No signature right now
    {{ DiscussionBoard.errors[7371369].message }}
  • Profile picture of the author mariya20
    Very nice solution and easy to add ! thank you
    {{ DiscussionBoard.errors[8078328].message }}
  • Profile picture of the author P4tch
    Another thing to do would be to use CloudFlare and use the HTTP_CF_IPCOUNTRY header (or something like that... header) that they send and route around with that.
    {{ DiscussionBoard.errors[8078403].message }}
    • Profile picture of the author SteveSRS
      Originally Posted by P4tch View Post

      Another thing to do would be to use CloudFlare and use the HTTP_CF_IPCOUNTRY header (or something like that... header) that they send and route around with that.
      You should read the thread before providing an answer which has already been said
      {{ DiscussionBoard.errors[8088906].message }}
      • Profile picture of the author Geolify
        hi guys,

        we have just released an awesome tool that can be used to create geo targeted redirects for you website.

        this tool is called geolify and you can sign up to use it by visiting geolify.com

        you can easily use this to create multiple redirects depending on vistor country, state, city and even IP address which is great for block spammers or redirecting visitors to more appropriate parts of your website based on their location.

        once you setup the redirects, you will be given a simple one line piece of code to add to your website header to make the geo redirect active.

        any feedback is welcome
        {{ DiscussionBoard.errors[9154041].message }}
  • Profile picture of the author Alexei Shaban
    Try out MagestyApps' GeoIP Store & Currency Switcher plugin for Magento
    {{ DiscussionBoard.errors[10726702].message }}

Trending Topics