How to Redirect domain according to country IP using PHP| .htaccess

In this tutorial, we will know how to redirect domain according to a country IP address. If you have a multi-country website and you want to redirect traffic as per users IP address then this tutorial is for you.

Actually, it is not a good practice to redirect a user as per their language or country. It can be far better if you could use some other way like:

  1. show a message at the top of your website that influences the visitor to go to the page built for a particular language.
  2.  show a dropdown type bar that can easily change the language or flags.

But in some cases, it is required to redirect domain according to IP address.  If your website is built on PHP and if you are using apache server then this method will work for you.

Redirect Domain Using PHP

First of all, you need to download Geo Plugin library from here. Now, include this library on your page and add the code snippet given below:

I have used functions.php file which is already included in all over the website files.

<?php
require_once('geoplugin.class.php');
$geoPlugin = new geoPlugin();
$geoPlugin ->locate();
$countryCode = $geoPlugin ->countryCode;

switch($countryCode) {
    case US:
       header('Location: http://us.example.com/');
        break;
    case GB:
       header('Location: http://gb.example.com/');
        break;
    case FR:
       header('Location: http://fr.example.com/');
        break;
    case IN:
       header('Location: http://example.com/');
        break;
}
?>

You can find the all country code list provided by Geo Plugin here so that you could create your domain redirect statement easily.

Using .HTACCESS

First of all, you need to configure & install mod_geoip module on your server. If it is already configured there then open the .htaccess file and paste the code showing below:

GeoIPEnable On
GeoIPDBFile /path/to/GeoIP.dat


# USA
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^US$
RewriteRule ^(.*)$ http://us.example.com$1 [L]
 
# UK
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^GB$
RewriteRule ^(.*)$ http://gb.example.com$1 [L]

# France
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^FR$
RewriteRule ^(.*)$ http://fr.example.com$1 [L]
 
# India
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$
RewriteRule ^(.*)$ http://in.example.com$1 [L]

Also Read:

 

 

One Response

Leave a Reply