I was once asked to block some countries on a web server running Apache2 and Ubuntu Server 20.04.
Since Apache2 was running on the server, I installed the GeoIP module for it, which is a bit outdated but installs quickly:
apt-get install libapache2-mod-geoip
After installation, the file appeared:
nano /etc/apache2/mods-enabled/geoip.conf
In which I indicated which countries I was asked to block:
<IfModule mod_geoip.c>
GeoIPEnable On
GeoIPDBFile /usr/share/GeoIP/GeoIP.dat
GeoIPDBFile /usr/share/GeoIP/GeoIPv6.dat
SetEnvIf GEOIP_COUNTRY_CODE RU BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE IN BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE VN BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE BD BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE PK BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE ID BlockCountry
Deny from env=BlockCountry
</IfModule>
The country code can be found here wikipedia.org/wiki/ISO_3166-1
After the changes, we will check the correctness of the apache2 configuration:
apachectl -t
And any of the commands below will apply the changes:
service apache2 reload
service apache2 restart
Now it remains to specify which sites to apply BlockCountry to, you can specify it directly in the site configuration file:
<Files ixnfo.com.txt>
order deny,allow
deny from env=BlockCountry
</Files>
<Directory /var/www/ixnfo.com/>
order deny,allow
deny from env=BlockCountry
</Directory>
You can also register an account on maxmind.com to get a free license key and update the free database, but as I understand it, it is already in a different format and the file is not called GeoIP.dat.
Installing the auto update script:
apt-get install geoipupdate
After installation, the /etc/cron.d/geoipupdate and /usr/share/doc/geoipupdate tasks were added.
For the update to work, you need to specify the registration data:
nano /etc/GeoIP.conf
AccountID
LicenseKey
EditionIDs
To manually update, run (in your account on the maxmind.com website you will see which databases were requested):
geoipupdate
You can also manually check which country the IP address belongs to:
geoiplookup X.X.X.X
See also my articles:
Information about using .htaccess
More about Apache2