Allow or Block IP/IP range or country from accessing website using .htaccess
Sometimes you want to block/allow any certain IP or an IP range either for security reason or even to disallow bots or humans to access your website. You can easily do this by restricting/allowing those IP or IP ranges in .htaccess file.
Allow/Block IP address:
For Example you want to block certain IP/IP range to access your site, you will write following lines in your .htaccess
Above lines will block access to your site from 220.127.116.11 IP address.
Now suppose you want to do converse if this, meaning you want to allow access to your site only from 18.104.22.168 IP then
you need to write following in your .htaccess file”
Allow/Block IP range:
To Block access from a certain IP range, you will write following in your htaccess file:
Above lines will disallow to access website from any IP from 22.214.171.124 to 126.96.36.199
To Allow access only from a certain IP range, you will write following in your htaccess file:
Above will allow access to your website from 10.10.11.1 to 10.10.11.25 IPs.
Allow / Block Countries to access website
In similar fashion, we can even allow/block any country or countries from accessing our website. For this the logic is same, we will allow/block all the possible IP ranges for that particular country or countries.
For this we will use 3rd party tools which will generate .htaccess code for us and we will just paste that in our .htaccess. Some of the online generators are:
Here, we will use www.ip2location.com for our example.
we will allow access only from India to website, then we will build our code as shown in screen-shot:
Now, we just have to copy paste this code in our .htaccess file on root folder and it will block all other countries to access your website.