GeoIP blocking and redirecting on Apache
Recently I was asked to configure a WordPress install to block any traffic from Russia, and redirect any traffic from the USA to another US-centric site.
First thing to do is install mod-geoip
for Apache (in my case on Ubuntu):
sudo apt install libapache2-mod-geoip
Next uncomment the GeoIP database in the GeoIP conf file (/etc/apache2/mods-available/geoip.conf
):
<IfModule mod_geoip.c>
GeoIPEnable On
GeoIPDBFile /usr/share/GeoIP/GeoIP.dat
</IfModule>
Restart Apache:
sudo systemctl restart apache2
With GeoIP enabled we can apply our block and redirect in .htaccess
GeoIPEnable On
# deny for Russia
SetEnvIf GEOIP_COUNTRY_CODE RU DenyCountry
# redirect for USA
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(US)$
RewriteRule ^(.*)$ https://usa-site.com/$1 [L]
A list of ISO Alpha-2 country codes can be found on WikiPedia, and many other places online.