How to block threats using CloudFlare Geolocation

CloudFlare is a great tool to help protect your website, there are plenty of blog posts about why so I won’t repeat that again here. One way to increase your security is to limit access to the admin pages of your website. If you have a fixed IP Address e.g. in your office at work then it is relatively easy to restrict access to just that address however if you or others need to access when on the go then this is too restrictive.

One solution that can prevent a lot of hacking attempts to block access to IP’s outside your home country.

On the CloudFlare network screen you can enable IP Gelocation, it looks like this:

CloudFlare IP Geolocation

CloudFlare adds an extra HTTP header which you can access with Apache (code this within your Apache configuration file) and use to set a variable with the SetEnvIf directive. In the example below if the IP is from the UK, I set a variable to true:

SetEnvIf HTTP_CF_IPCOUNTRY GB NoBlock=true

Next you can check the value of that variable and issue rewrite directives accordingly, here is the full code which will issue an HTTP 403 Forbidden if they are not in the UK and trying to access a URL containing an admin path:

  RewriteEngine on
  # block access if not UK
  # send them Forbidden, no further rules evaluated
  SetEnvIf HTTP_CF_IPCOUNTRY GB NoBlock=true
  RewriteCond %{ENV:NoBlock} !^true$
  RewriteCond %{REQUEST_URI} ^/index.php/admin/(.)*
  RewriteRule .* - [F]

I have found this to be incredibly effective at stopping hacking attempts.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA - answer the question below to prove you are human *

This site uses Akismet to reduce spam. Learn how your comment data is processed.