In this tutorial we’ll talk about how to redirect domain according to country IP address using php and .htaccess, You can write .htaccess rules that filters and redirect traffic based on country. If you have multi country website and you are looking for a solution to automatically user should redirected to their origin country then this tutorial is for you. You can implement redirection in both way in php or using .htaccess.
redirect-domain-according-to-country-ip-address
Suppose you have three sub domain like http://au.example.com, http://us.example.com, http://in.example.com Australia, USA, India.
And If some one type http://example.com then he/she redirected county specific url as per geo ip location.



Here is the solution.

By PHP

First of all download geoplugin library and call it on your page.
http://www.geoplugin.com/_media/webservices/geoplugin.class.phps

require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
$countryCode = $geoplugin->countryCode;
switch($countryCode) {
    case AU:
       header('Location: http://au.example.com/');
        break;
    case US:
       header('Location: http://us.example.com/');
        break;
    case IN:
       header('Location: http://in.example.com/');
        break;
}
?>

Here is the country code list for geoplugin and you can find easily.
http://www.geoplugin.com/iso3166


By .htaccess

First you need to check that you have the mod_geoip module (GeoIP Extension) installed and configured on your server, If yes then tweak your .htaccess file accordingly..

GeoIPEnable On
GeoIPDBFile /path/to/GeoIP.dat
 
# Start Redirecting countries
 
# Australia
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^AU$
RewriteRule ^(.*)$ http://au.example.com$1 [L]
 
# USA
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^US$
RewriteRule ^(.*)$ http://us.example.com$1 [L]
 
# India
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$
RewriteRule ^(.*)$ http://in.example.com$1 [L]
 
# and so on..

If you like this post please don’t forget to subscribe my public notebook for more useful stuff