On this page

Deny Or Allow Countries With Apache .htaccess

Introduction

The following script is using blogama.org IP geolocation API to automatically generate Apache .htaccess file to deny or allow specific countries. You can put this script under crontab and the .htaccess rules will be automatically updated. Also, it can update multiple .htaccess files.

Deny or allow?

First you need to understand the meaning of these two rules in the .htaccess file. If you set "deny" in the script for countries "US,CA" (USA and Canada), all traffic from USA or Canada will be blocked. On the other hand, if you set "allow" it will only accept traffic from these two countries, all others being blocked.

Countries code

You need to know the ISO country code you want to deny/allow. The list is available here.

Usage without the automated script

Where country is the list or countries, with a comma between them and output is either htaccess_deny or htaccess_allow.

How is the script working?

You will have to create a text file with all .htaccess files (with complete path) you wish to update with the script. If you have other information in your .htaccess files they will still remain there, the script will only update the portion between the tags "#COUNTRY_BLOCK_START" and "#COUNTRY_BLOCK_END".

Before you start with the script

Create a text file named htaccessfile.txt (in the WORKDIR of the script, see below). In that file, put all (existing!) .htaccess files you wish to update. For example:

/var/www/example.com/.htaccess
/var/www/mydomain.com/.htaccess

Script configuration

On top of the script, you will find this section. You need to modify these variables if needed:

WORKDIR: is a writable directory where the script will be located.HTACCESSFILE: is the file where you will put your .htaccess paths.HTACCESSBLOCK and TEMPFILE: are temporary file that will be deleted at the end of the script execution.COUNTRIES: is the list of countries you wish to deny/allow, separated with a comma.TYPE: "allow" or "deny" access to these countries.