How to install GeoIP and block foreign traffic

Posted on February 5th, 2007 by rookie
Normally I wouldn’t post technical articles like this since I want to focus this blog on marketing but I felt the need to write about this one since I couldn’t find much info about it when I needed guidance. GeoIP is useful when you want only a certain demographic to access your websites. In advertising, U.S traffic pays the best, followed by U.K and Canada.
There are several ways to accomplish this, so the method I am about to go over is definitely not the “only one.” I will also be assuming that your server is running a linux distro and that you have root privileges.
First, you need to download the latest GeoIP API in C to your linux server:
Extract the contents:
tar -zxvf GeoIP-1.4.1.tar.gz
Run “./configure” inside the extracted directory. This will make sure that this software is compatible with your system. After it is done configuring, run the commands “make” and “make install”
cd GeoIP-1.4.1
make install
Next, we have to install the geoip PHP extension. This is very easy if you have the php-devel package already installed on your system.
pecl install geoip-0.2.0
Create a new .ini file inside your /etc/php.d/ directory to enable the geoip extension module. You can also do this by editing the php.ini file but it’s neater this way. Call it geoip.ini and add the following lines in there.
; Enable GeoIP extension module
Using this geoip module, let’s write a simple php script to only allow traffic from the U.S, U.K, Canada and Australia. If the traffic does not match this criteria, they will see a blank page. Add this code at the top of all the php pages that you want to limit access on:
   # Block foreign traffic
   $country = geoip_country_code_by_name($_SERVER["REMOTE_ADDR"]);
   if (!(($country == "US") or ($country == "CA") or ($country == "GB") or ($country == "AU"))) { die; }
index.php, about.php, contact.php, etc. Please note that this will not work on regular html pages; this is for php pages only.
Restart apache and everything should be working as planned.

Note: This article originally appeared at, but that web site is no longer online. If you are the owner of this content and object to this placement, please contact me.