In 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.


