• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy

How to Redirect Visitors based on IP Location

Afsal

  • 7 min read
How to Redirect Visitors based on IP Location

Generating audio, please wait...

Location Based Redirection

Location based redirection is a technique that is useful when you want to redirect traffic to your website to different parts of your websites or to your sub-domains based on the visitor’s geographic location. Let us see how to redirect visitors based on IP location

The redirection method I am using here is done with the help of 2 files,i.e, a PHP script file and a text file.

Text File:

The text file contains the IP ranges that is specific to a country. For example, the text file containing the IP ranges specific to Germany looks like the following. This is just representative data, you need to get the actual ones for the proper functioning of the script

2.16.6.0/23
2.16.12.0/23
2.16.22.0/23
2.16.24.0/23
2.16.28.0/22
2.16.32.0/23
2.16.36.0/23
2.16.46.0/23
2.16.48.0/23
2.16.61.0/24
2.16.62.0/24
2.16.64.0/24

PHP Script:

The PHP script is used to fetch the list of IPs from these CIDR ranges and redirect the user based on their IP. The script is given below.


<?php
function checkUserIP($user_ip, $cidrs) {      // Function to get IP list from range
    $ipu = explode('.', $user_ip);
    foreach ($ipu as &$v)
    $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
    $ipu = join('', $ipu);
    $res = false;
    foreach ($cidrs as $cidr) {
                $parts = explode('/', $cidr);
                $ipc = explode('.', $parts[0]);
                foreach ($ipc as &$v)
                $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
                $ipc = substr(join('', $ipc), 0, $parts[1]);
                $ipux = substr($ipu, 0, $parts[1]);
                $res = ($ipc === $ipux);
                if ($res) break;
    }
  return $res;
}
 
 
$user_ip = $_SERVER['REMOTE_ADDR']; // get user ip
 
// Don't change the above part
 
 
// Custom code suited to your setup.
 
$f1 = 'ip.txt';  // Text file with IP ranges.
 
if (checkUserIP($user_ip, file($f1, FILE_IGNORE_NEW_LINES))) {  // Compare user IP with the IP list from text file.
 header("Location: <location>");   // Specify the location to which to redirect to.
}

The above script will compare the user’s IP with the IP ranges in the text file ‘ip.txt’ and performs redirection based on the output.

How it works?

I am going to show an example of a situation which uses the above script to redirect users based on their country.

For testing purpose, I have created a simple website iptestsite.cf. It has an index file for the main site and there are two directories ‘de’ and ‘fr’.

The following are the contents of the public_html directory.

[/home/u538987939/public_html/] ls -l
drwxr-xr-x 2 u538987939 u538987939   4096 Mar 23 02:20 de         
-rw-r--r-- 1 u538987939 u538987939 883690 Mar 23 01:52 deip.txt
drwxr-xr-x 2 u538987939 u538987939   4096 Mar 23 02:27 fr
-rw-r--r-- 1 u538987939 u538987939 468112 Mar 23 01:51 frip.txt
-rw-r--r-- 1 u538987939 u538987939     37 Mar 23 01:41 index.php

-rw-r--r-- 1 u538987939 u538987939   1009 Mar 23 02:16 ip.php   

I am going to redirect the visitors from Germany to the directory ‘de‘ and visitors from France to the directory ‘fr‘ and everyone else to public_html/index.php.

The public_html/index.php file contains the following contents.


<?php require("ip.php"); // The index.php will only work after the execution of ip.php
?>    
Home Page

The ‘ip.php’ file contains the PHP script mentioned earlier modified to suit our current purpose.

<?php
function checkUserIP($user_ip, $cidrs) {
    $ipu = explode('.', $user_ip);
    foreach ($ipu as &$v)
    $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
    $ipu = join('', $ipu);
    $res = false;
    foreach ($cidrs as $cidr) {
                $parts = explode('/', $cidr);
                $ipc = explode('.', $parts[0]);
                foreach ($ipc as &$v)
                $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
                $ipc = substr(join('', $ipc), 0, $parts[1]);
                $ipux = substr($ipu, 0, $parts[1]);
                $res = ($ipc === $ipux);
                if ($res) break;
    }
  return $res;
}
 
$f1 = 'frip.txt';        // File that contains IP ranges specific to France.
$f2 = 'deip.txt';        // File that contains IP ranges specific to Germany.
$user_ip = $_SERVER['REMOTE_ADDR']; // get user ip
// checking user ip address redirect
 
if (checkUserIP($user_ip, file($f1, FILE_IGNORE_NEW_LINES))) {
 header("Location: http://iptestsite.cf/fr");  // Redirect to 'fr' if user IP belongs to frip.txt
}
 
elseif (checkUserIP($user_ip, file($f2, FILE_IGNORE_NEW_LINES))) {
 header("Location: http://iptestsite.cf/de");  // Redirect to 'de' if user IP belongs to deip.txt
}
?>

The ‘frip.txt’ contains IP ranges specific to France and ‘deip.txt’ contains IP ranges specific to Germany in the format mentioned earlier. You can get the IP ranges list from the URL http://www.ip2location.com/blockvisitorsbycountry.aspx. From there select the country and choose output format as CIDR.

ip2location-png

Here are the contents of the directories ‘de’ and ‘fr’.

$[/home/u538987939/public_html/] ls-l de
total 8
-rw-r--r-- 1 u538987939 u538987939 877 Mar 23 02:23 deip.php
-rw-r--r-- 1 u538987939 u538987939  38 Mar 23 02:25 index.php
u538987939$ [/home/u538987939/public_html/] ls-l fr
total 8
-rw-r--r-- 1 u538987939 u538987939 877 Mar 23 02:27 frip.php

-rw-r--r-- 1 u538987939 u538987939  38 Mar 23 02:26 index.php


The public_html/de/index.php file contains the following.


<?php require("deip.php"); 
?>
DE Home

The ‘public_html/de/deip.php‘ file is used to redirect the IPs that does not belong to Germany to main site.


<?php
function checkUserIP($user_ip, $cidrs) {
    $ipu = explode('.', $user_ip);
    foreach ($ipu as &$v)
    $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
    $ipu = join('', $ipu);
    $res = false;
    foreach ($cidrs as $cidr) {
                $parts = explode('/', $cidr);
                $ipc = explode('.', $parts[0]);
                foreach ($ipc as &$v)
                $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);
 
                $ipc = substr(join('', $ipc), 0, $parts[1]);
                $ipux = substr($ipu, 0, $parts[1]);
                $res = ($ipc === $ipux);
                if ($res) break;
    }
  return $res;
}
 
 
$f1 = '../deip.txt';
 
 
$user_ip = $_SERVER['REMOTE_ADDR']; // get user ip
 
// checking user ip address redirect
 
 
if (!checkUserIP($user_ip, file($f1, FILE_IGNORE_NEW_LINES))) { 
 header("Location: http://iptestsite.cf"); // Redirect IPs that does not belong to Germany to main site.
}
 
?>

The directory ‘fr’ uses a similar setup to redirect the IPs that does not belong to France to main site.

Testing:

For testing the site from multiple locations, I am going to use http://www.locabrowser.com/. I am going to test the website from France, Germany, US, Singapore.

First we will access the main site ( http://iptestsite.cf ) from these locations.

main-png

 

 

 

 

We get the following outputs.

main1-png

main2-png

main3-png

main4-png

As you can see, the IP from Germany is being redirected to ‘de’ and the IP from France ‘fr’.

Now we will try accessing one of the subdirectories ( http://iptestsite.cf/fr ) directly from these locations.

fr-png

We get the following output.

main11-png

main22-png

main33-png

main44-png

As you can see, the output looks same as before. What happened was, the IPs that does not belong to France was redirected to the main website. From there, the IP that belongs to Germany was again redirected to ‘de’.

Get 24/7 expert server management

  • Linux
How to Redirect Visitors based on IP Location

Introduction to Magento2 Command Line Interface (CLI)

Introduction to Magento2 Command Line Interface (CLI)
  • Linux
  • magento
logo

Magento2: Configuration File

Magento2: Configuration File
  • Linux
  • magento
logo

PHP script to Change MySQL Table Prefix

PHP script to Change MySQL Table Prefix
  • Howtos
  • Linux
  • magento
  • MySQL
  • WordPress
logo

Steps to enable TLSv1.2 for PayPal /Stripe connections

Steps to enable TLSv1.2 for PayPal /Stripe connections
  • Howtos
  • Linux
  • Troubleshooting
logo

Posts by Afsal

Afsal is a tech enthusiast who is always ready to learn new technologies and explore new territories. Although his current focus revolves around the System Administration world, his never ending passion for technologies always keeps him active in other areas as well. He is currently working as a Systems Engineer at SupportSages.