DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Install OroCRM on Ubuntu 20.04
  • Deploying a Simple Golang Web App on Heroku
  • Deploy a Hyperledger Fabric v2 Web App Using the Node.js SDK
  • Generating a Trusted SSL Certificate (Node Example)

Trending

  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Agentic AI for Automated Application Security and Vulnerability Management
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  1. DZone
  2. Coding
  3. Languages
  4. How to Implement Geolocation Features in Apache Server

How to Implement Geolocation Features in Apache Server

This article will guide you on how to add geolocation features in Apache Server and get to know the geolocation of your visitor.

By 
camimi Morales user avatar
camimi Morales
·
Dec. 15, 22 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.3K Views

Join the DZone community and get the full member experience.

Join For Free

Geolocation, a technology is allowing you to find out where your visitor’s location by using an IP address, is a 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 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 an Apache server and touch base on 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 is sent over to your PHP program for further processing. This is also a logically good place to place your control or logic, such as to redirect, block, or 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 set up 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 are different from your standard Apache installation, to build the module. You can run the below command to set up the development environment.

Shell
 
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.

Shell
 
mkdir ip2location && cd ip2location


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

Shell
 
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: 

Shell
 
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.

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


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

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


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

 the commands are running successfully.
 


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

Then, go into the ip2location-apache-master folder.

Shell
 
cd ../ip2location-apache-master/


Build the IP2Location Apache module by running the below command: 

Shell
 
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.

 the module was built successfully.
 


Restart the Apache server to activate the module.

Shell
 
service apache2 restart


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

Shell
 
apache2ctl -M


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

see the IP2Location_module (shared) entry.
 


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.)

Shell
 
a2enmod rewrite


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

Shell
 
apachectl -M


the rewrite module has been enabled.
 

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.

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


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

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

Plain Text
 
<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:

Plain Text
 
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 Google.

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

Plain Text
 
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 third 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 below will return 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
 
<?php
echo $_SERVER[IP2LOCATION_COUNTRY_SHORT];
echo $_SERVER[IP2LOCATION_REGION];
echo $_SERVER[IP2LOCATION_CITY];
?>


Conclusion: Pros and Cons

Every approach has its pros and cons, and it’s just a matter of what fits your environment the best. The above approach provides you with 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 with a faster and more 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 okay with the restart activity, then that would be no problem at all. 

Happy coding.

HTTPS Library PHP Plain text Relational model Web server Command (computing) shell

Published at DZone with permission of camimi Morales. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Install OroCRM on Ubuntu 20.04
  • Deploying a Simple Golang Web App on Heroku
  • Deploy a Hyperledger Fabric v2 Web App Using the Node.js SDK
  • Generating a Trusted SSL Certificate (Node Example)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!