The GeoIP module is used to find which Geolocation or area is used by the IP from IP location database. We can setup country based redirection rule in htaccess for Magento2 which will redirect the required stores to the specific countries.
To add rules for country based redirection in Magento we have to install the GeoIP module.

The below installation needs to be done on a centos 7 server and if you need this to be done from our end or need help to setup on any other OS, Click here to contact our experts to get it done right now.

Install GeoIP and dependencies

yum install GeoIP GeoIP-devel GeoIP-data zlib-devel

Change the directory to the /usr/share/GeoIP/, upload and extract GeoIP database in this location
You can download the GeoIP database from https://dev.maxmind.com/geoip/geoip2/geolite2/

cd /usr/share/GeoIP/
tar -xzvf GeoLite2-ASN_20200630.tar.gz

Install the required packages for GeoIP

yum install httpd-devel apr-devel ea-apache24-devel.x86_64 ea-apache24-tools.x86_64

 Download and extract GeoIP module using the below steps

wget https://github.com/maxmind/geoip-api-mod_geoip2/archive/1.2.10.tar.gz
tar -xzvf 1.2.10.tar.gz
cd mod_geoip2_1.2.10
sed s/remote_ip/client_ip/g -i mod_geoip.c

Compile and install the GeoIP module

apxs -i -a -L/usr/lib64 -I/usr/include -lGeoIP -c mod_geoip.c

Load the module in Apache at Apache modules conf.

vim /etc/apache2/conf.modules.d/mod_geoip.conf

###########
LoadModule geoip_module /usr/lib64/apache2/modules/mod_geoip.so

<IfModule mod_geoip.c>
GeoIPEnable On
GeoIPScanProxyHeaders On
GeoIPDBFile /usr/share/GeoIP/GeoIPASNum.dat Standard
GeoIPDBFile /usr/share/GeoIP/GeoIPCity.dat Standard
</IfModule>
###########

Check Apache Configuration and restart Apache

httpd -t
service httpd restart

Verify if GeoIP module is enabled by

httpd -M | grep geoip

You can see the result as shown below

Next, we have to add the rule for redirection of countrywide access in Magento2 site. There are certain country codes available for GeoIP database. We can use that country codes here to add rules in .htaccess.

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(GB|RU|IN)$
RewriteCond %{REQUEST_URI} !^/store/
RewriteRule .* https://www.example.com/store/ [L]
</IfModule>

where GB|RU|IN are the country codes for UK, Russia and India

Restart Apache

service httpd restart

According to the above rule, the users accessing from UK and Russia and India for /store of https://www.example.com, will redirect to https://www.example.com/store.
By using GeoIP module we can also block and deny countrywide access to the site.

Are you struggling with managing your server?

check our management plans here