Securing Website through .htaccess behind CloudFlare or CDN

access-denied

By default, when you want to block or allow some IP(s) from your website, you may simply do it as the following rules from .htaccess,

order deny,allow
deny from all
allow from 1.1.1.1
allow from 2.2.2.2

However, if you are using service like CloudFlare or other CDN service, you can not do like this as Apache do not understand your visitor IP.

To do that, you need to do like rules below,

SetEnvIf X-FORWARDED-FOR 1.1.1.1 allow
SetEnvIf X-FORWARDED-FOR 2.2.2.2 allow
order deny,allow
deny from all
allow from env=allow

If you need it for IP ranges or network block such as 1.1.1.0/24, you may do it like,

SetEnvIf X-FORWARDED-FOR "^1\.1\.1\.*" allow
order deny,allow
deny from all
allow from env=allow

cPanel: How to block visitor by country through GeoIP

To block a certain country IP range, you do not need to know which IP range it is and what you need is to use the GeoIP feature.

To install GeoIP, refer to the following URL,
http://www.mickgenie.com/cpanel-how-to-install-mod_geoip

Next, you will need to insert the following command to the .htaccess file,

RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CN$
RewriteRule ^(.*)$ http://www.google.com [L]

The command use to redirect China IP to google.com***

***This is an example only and it is not to abuse any user/visitor reside in China.