How to Redirect Visitors Based on Country or IP Address?

Tommyhara

Verified User
Joined
Jul 25, 2014
Messages
162
I want to redirect Visitors Based on their Country or IP Address. How can I do that with Directadmin and htacess?

For examples:
A person from UK will be redirected to this url: example.com/uk/
A person from US will be redirected to this url: example.com/us/
Default users from other countries will use this url: example.com

I heard that it is possible to install a Geo IP addon and set code in httacess but not sure how to do. Any guide?
 

Richard G

Verified User
Joined
Jul 6, 2008
Messages
4,395
Location
Maastricht
An easy search on the internet come up with this result:

Code:
GeoIPEnable On
GeoIPDBFile /path/to/GeoIP.dat

# Start Redirecting countries

# Canada
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA$
RewriteRule ^(.*)$ http://ca.abcd.com$1 [L]

# India
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$
RewriteRule ^(.*)$ http://in.abcd.com$1 [L]
Adjust country codes and redirection url to your needs.

You need the apache mod_geoip2 module for this to work:
https://dev.maxmind.com/geoip/legacy/mod_geoip2/

On that page there is also a link to mod_geoip if you're still using Apache 1.
 
Last edited:

zEitEr

Super Moderator
Joined
Apr 11, 2005
Messages
14,161
Location
GMT +7.00
Installation instructions can be found here: https://github.com/maxmind/geoip-api-mod_geoip2/blob/master/INSTALL.md

install

Code:
cd /usr/local/src
wget https://github.com/maxmind/geoip-api-mod_geoip2/archive/1.2.10.tar.gz -O GeoIP.1.2.10.tar.gz
tar -zxvf GeoIP.1.2.10.tar.gz
cd geoip-api-mod_geoip2-1.2.10/
apxs -i -a -L/usr/local/lib -I/usr/local/include -lGeoIP -c mod_geoip.c
/usr/local/directadmin/custombuild/build rewrite_confs
activate module

Code:
echo "LoadModule geoip_module       /usr/lib/apache/mod_geoip.so" >> /etc/httpd/conf/extra/httpd-includes.conf
restart Apache and test


Code:
# apachectl -M 2>&1 | grep geoip
geoip_module (shared)
 

Tommyhara

Verified User
Joined
Jul 25, 2014
Messages
162
Thanks zEitEr for useful guide!

I also found codes to redirect visitors based on country that using .htaccess from their page, I could apply for my website

GeoIPEnable On
GeoIPDBFile /path/to/GeoIP.dat

# Redirect one country
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA$
RewriteRule ^(.*)$ https://www.bantranh.com$1 [R,L]

# Redirect multiple countries to a single page
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(CA|US|MX)$
RewriteRule ^(.*)$ https://www.bantranh.com$1 [R,L]

but I don't know if I use this way, can it affect to loading/performance for my website and web page?


Thanks
 

zEitEr

Super Moderator
Joined
Apr 11, 2005
Messages
14,161
Location
GMT +7.00
The best way to learn it is to try it, you can always revert the changes back.

Any redirect will cause additional time delay for a final page to load.
 
Top