I was requested to prevent access to a website. There are two ways I know I can choose - 1. At apache level (a tool like this: http://www.ip2location.com/blockvisitorsbycountry.aspx) which generates a long htaccess file with list of IP ranges. The other way I know of is using PHP (be it a local DB, remote webservice or just a list just like the htaccess). My question is what is more effective - I think that if I use apache, it is faster then PHP but done each and every page accessed. If I use PHP, I can do it once and save in the session. What is the more efficient way? Thanks!
Best How To :
You don’t have to fill your
.htaccess file with thousands of lines of IPs. Instead, you can install a C library and an Apache module to do the heavy lifting for you.
MaxMind provides a popular free database that is often used for IP lookups. Their GeoLite2 is a free database that is updated monthly. Their paid product is more accurate and updated more frequently if you require that.
By using this database and installing one of their various
APIs, you can handle traffic as you see fit.
For our purposes, you would need to install the C library API as well as the Apache module. Once those are working and enabled, place the database file somewhere, and then you can set up your country blocks with code as simple as this in the
Apache config file:
MaxMindDBFile DB /path/to/GeoIP/GeoLite2-Country.mmdb
MaxMindDBEnv MM_COUNTRY_CODE DB/country/iso_code
SetEnvIf MM_COUNTRY_CODE ^(RU|DE|FR) BlockCountry
Deny from env=BlockCountry
This would block Russia, Germany, and France. Get your two-letter ISO country codes here.
This would perform much better than your server having to parse thousands of lines of text on every request in the .htaccess file!
You do need advanced access to your server to install the library and module, so this is no good on shared hosts or where you don’t have such access on a VPS.
This would also work if, for some reason, you wanted specific blocking rules at the folder level.
Nice Article / Reference