DEV Community

Cover image for How to implement geolocation features in Apache Server
IP2Location
IP2Location

Posted on • Updated on

How to implement geolocation features in Apache Server

Geolocation, a technology allowing you to find out where your visitor’s location by using an IP address, is an ubiquitous solution that has been used in many industries. For example, if you are using Google Analytics or Matomo to track your visitors, you are using the geolocation solution. If you embed a cool widget to automatically fill the country or region information, you are using the geolocation solution. To name a few.

There are many reasons to implement the geolocation, such as to better serve your audiences, to tailor make a better browsing experience, to monitor the buying pattern, to combat fraud, and so on. In this article, I’m going to show you how to implement the geolocation features in Apache server, and touch base some usage scenarios. Here, I will use the IP2Location geolocation library for Apache, PHP programming language and Debian OS.

The web server modules

Web server is the software to handle the HTTP/HTTPS requests so that the visitor can view and access your websites. This would be the first layer of processing before the request being sent over for your PHP program for further processing. This is also a logically good place to place your control or logic, such as to redirect, to block or to deliver a response back to the caller. For example, to block the users coming from a specific country that you do not have the business present or services, or, to redirect the Korean viewers to your Korean translated pages.

Prerequisite

In this tutorial, I will use Apache 2.4.54 in Debian 11 for the explanation. And, I will assume you have this environment setup to follow the below sequences.

Also, please make sure you have the unzip and wget packages installed.

The Apache

In order to use the geolocation feature in the Apache environment, you will need to build and install the module into the Apache server. You will need to install the development tools, which is different from your standard Apache installation, to build the module. You can run the below command to set up the development environment.

sudo apt install apache2-dev

The IP2Location Apache module

The IP2Location Apache module is built using IP2Location C Library. Before you can build the module, you will need to download and install the C library. I will create a folder called ip2location for this building process.

mkdir ip2location && cd ip2location

Inside the ip2location folder, we will download the IP2Location C library by running the below command.

wget https://github.com/chrislim2888/IP2Location-C-Library/archive/master.zip
unzip master.zip && rm master.zip

Besides, we will also download the IP2Location Apache module by running the below command:

wget https://github.com/ip2location/ip2location-apache/archive/refs/heads/master.zip
unzip master.zip && rm master.zip

You should see both the IP2Location-C-Library-master and ip2location-apache-master inside the ip2location folder.

Implement geolocation features in Apache Server

Next, we are going to build and install the IP2Location C library. Execute the below commands:

cd IP2Location-C-Library-master
autorecof -i -v --force
./configure
make
make install

You should see the below screenshot if the commands are running successfully.

Implement geolocation features in Apache Server

Please execute the ldconfig command to reload the shared library in Debian.

Then, go into ip2location-apache-master folder
cd ../ip2location-apache-master/

Build IP2Location Apache module by running the below command:
apxs2 -i -a -L ../IP2Location-C-Library-master/libIP2Location/ -I ../IP2Location-C-Library-master/libIP2Location/ -l IP2Location -c mod_ip2location.c

You should see the below screen if the module was built successfully.

Implement geolocation features in Apache Server

You need to restart the Apache server to activate the module.
service apache2 restart

Then, run the following command to confirm if the module has been enabled inside Apache Server.

apache2ctl -M

If the above procedures were done correctly, you should see the IP2Location_module (shared) entry as shown in the following screenshot.

Implement geolocation features in Apache Server

Now, we have the module ready. Let’s explore how to use the module.

Redirect users to a specific URL

You can redirect the users to a specific URL at the Apache server before the request routes to your PHP page. Why do we want to do so? It’s because this approach could give you a faster response time and low CPU usage, as the request does not need to be sent to PHP for extra processing. In this example, I will show you how to do so using the .htaccess file.

First of all, you must enable the rewrite module that allows you to perform the rewrite operation to the incoming URL. Run the following command to enable the rewrite module (It comes with Apache server installation, therefore no additional installation would be necessary)

a2enmod rewrite

Then, restart your Apache Server to activate the changes. Once restart, run the below commands make sure the rewrite module has been enabled.

apachectl -M

Implement geolocation features in Apache Server

Then, we need to add the IP2Location Apache configuration into the apache2.conf file. You can locate the file at the /etc/apache2 folder. Please add the following lines into the apache2.conf file.

<IfModule mod_ip2location.c>
IP2LocationEnable ON
IP2LocationDetectProxy OFF
IP2LocationSetmode ALL
IP2LocationDBFile /var/www/html/DB1.BIN
</IfModule>

You may refer to the information in the IP2Location Apache Module, to learn more about the settings. In this tutorial, you just need to paste the above and make sure the IP2LocationDBFile was pointed to the where you downloaded the BIN data file. You may download it from IP2Location LITE if you do not have one.

Inside the apache2.conf file, please make sure that the AllowOverride is set to All to allow the rewrite action the settings inside the .htacess file:

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all denied
</Directory>

You can now go to /var/www/html (the root directory of your domain) and create the .htaccess file and enter the following:

RewriteEngine On
RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^US$
RewriteRule ^(.*)$ https://www.google.com [L]

The above will redirect the traffic coming from the United States to https://www.google.com

Instead, if you would like to block the visitors by returning 404 page, you can do so as the following:

RewriteEngine On
RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^US$
RewriteRule ^(.*)$ - [R=404]

The [R=404] flag will instruct the web server to return the default 404 status back to the caller.

How to use the geolocation in PHP

Once you have the Apache module installed, you do not need to explicitly import a 3rd party geolocation library. The geolocation information is automatically made available via the environment variables and ready to use anywhere in your PHP project. A simple code as below will return you the country short name, region name and city name of the visitor’s IP address. Please note that you have to use DB3 BIN data in order to retrieve the region and city information.

<?php
    echo $_SERVER[IP2LOCATION_COUNTRY_SHORT];
    echo $_SERVER[IP2LOCATION_REGION];
    echo $_SERVER[IP2LOCATION_CITY];
?>
Enter fullscreen mode Exit fullscreen mode

Conclusion: Pros and Cons

Every approach has its pros and cons, and it’s just the matter of what fits your environment the best. For the above approach, it provides you an easy and faster way to retrieve the geolocation that you could use throughout all your PHP projects hosted under the same Apache server. One setup for all. Also, it provides you a faster and efficient way to perform redirection/blocking at the web server level. However, the main concern I can think of is the BIN file update. As you are aware that the BIN path was configured inside the apache2.conf and will only be loaded during the Apache loading process. Therefore, during the regular BIN data update, usually once a month, you have no choice but to restart the entire Apache server for the new BIN data to take effect. Having said that if you are not running a mission critical website, and are OK with the restart activity, then that would be no problem at all. The choice is yours.

Happy coding.

Top comments (0)