Allowing only CloudFlare traffic

No piratesIn other posts I give my point of view on the security advantages of using CloudFlare. But what’s to stop a bad guy, gal, or bot from accessing my site directly by IP address? I can try to keep my IP address secret, but a determined hacker will find it without too much trouble. He or she or his/her robot minions could then avoid CloudFlare security by attacking my site directly – unless I take explicit measures by allowing only CloudFlare traffic.

CloudFlare advises using directives in my htaccess file to allow traffic only from CloudFlare IPs. Problem is – that doesn’t work for me. My server is configured to see each visitor’s origin IP, not the CF IP, so that my visitor analytics make sense. I googled my fingers blue and could not find a solution.

In desperation – because I am a stereotypical guy who hates asking for directions – I asked for directions. A kind and knowledgeable person using the moniker sdayman┬ácame immediately to my rescue. It turns out he is a very prolific good Samaritan in the CloudFlare community.

Sdayman’s solution is elegant – three lines of code – and in my experience it works great:

RewriteEngine On
RewriteCond %{HTTP:CF-IPCountry} ^$
RewriteRule ^ - [F,L]

It checks to see if the CloudFlare IP Country header is present. If not, it serves a 403 error. Traffic bypassing CloudFlare will not have the header.

One small gotcha – I have to make sure I turn on the CloudFlare IP Geolocation feature. Easy-breezy. It’s on the Network screen.

Allowing only CloudFlare traffic

WPPOV supports freedom from Net Neutrality and the GDPR. The Internet of the people, by the people, for the people, shall not perish from the Earth.