How to Block IP Addresses or Countries to your Website Using .htaccess
Before you start:
We have a guide with instructions on how to access your .htaccess file
Block all access to your website:
Add this code to the top of the .htaccess file, then select Save
deny from all
Block access to your site from anyone but yourself:
Step 1 -
Use a website like ipchecker.com.au
to get your IPv4 address. Repeat this step for any other networks you'd like to be able to access the website.
Step 2 -
Add the following code to your .htaccess file, replacing <Your IP> with the IP you found. You can allow more IPs if necessary, then select Save
order deny, allow
deny from all
allow from 127.0.0.1
allow from <Your IP>
Block all access to your website from a specific country
If your site is getting unwanted traffic from a different country, you can easily use the GeoIP tool to block that country. This assumes your website isn’t intended for visitors from that country. A list of all country codes can be found here
Please bear in mind that if you block your own country, you will still be able to access cPanel, but you will not be able to view the website until the block is removed. Also note that VPNs and private IPs may have unexpected results here.
Add the below code to the top of your .htaccess file, then select Save
# Add countries you wish to deny here
SetEnvIf GEOIP_COUNTRY_CODE CO DenyCountry
SetEnvIf GEOIP_COUNTRY_CODE EG DenyCountry
SetEnvIf GEOIP_COUNTRY_CODE HI DenyCountry
Allow from all
Deny from env=DenyCountry
You can also do the opposite and only allow specific countries to access your website. This is a great proactive security measure if, for example, you only intend to have Australian clients or visitors to your site.
# Put countries to allow here
SetEnvIf GEOIP_COUNTRY_CODE AU AllowCountry
SetEnvIf GEOIP_COUNTRY_CODE NZ AllowCountry
Deny from all
Allow from env=AllowCountry
Did you find this article useful?