How to Block Foreign Internet Traffic to Your Website by Country Code in .htaccess Using Cloudflare

There are a myriad of different ways to block internet traffic to your website from foreign countries.  Most of them cause a strain on your server by comparing each visitor’s ip address with a list of ip address ranges inserted in your htaccess file. There are also country traffic blocking services that are not free or cost a premium.

I’ve a free method of blocking foreign internet traffic to my websites that does not strain my servers and protects the website’s bandwidth from unwanted or unnecessary visitors. This is very useful for nationally oriented websites. For example, one of my printer website customers does business in the USA, Canada, England, Ireland, France, and Germany. So I can restrict access from visitors living in other countries. My method uses Cloudflare in conjunction with instructions coded inside the website’s .htaccess file. Here are the steps…

  1. Activate Cloudflare services for your domain’s DNS
  2. Edit your public facing htaccess file to include the following code:

    #Begin Allow from Country with Cloudflare
    #Enable GEO in Cloudflare
    #Put Country code below here and above order

    SetEnvIf CF-IPCountry US Targeted=1
    SetEnvIf CF-IPCountry CA Targeted=1

    Order deny,allow
    Deny from all
    Allow from env=Targeted
    #End Allow from Country with Cloudflare

  3. Be sure to include a SetEnvIf CF-IPCountry xx Targeted=1 line for each of the country codes (xx) for which you’d like to grant access.

Please Note: Cloudflare also provides free SSL (Secure Socket Layer) for your domain. If you are running a WordPress website, I’d recommend activating Cloudflare’s plugin and forcing SSL from within the plugin’s settings area.