Httpd – Denying access to website via htaccess based on http header

.htaccesshttpdlitespeed

I've been trying for ages to get this to work and I can't put my finger on it. What I'm trying to do is block access to a site from a number of countries, based on the CF-IPCountry header added by CloudFlare. I figured htaccess was a suitable way to do this.

We are running LiteSpeed 4.2.4 on top of DirectAdmin for a control panel.

The problem we having is the htaccess rule doesn't seem to do anything.

Here's the rule we tried:

SetEnvIf CF-IPCountry AU UnwantedCountry=1
Order allow,deny
Deny from env=UnwantedCountry
Allow from all

That makes no difference at all, connections are still accepted. Just to check that the rule was at least being processed, I changed Allow from all to Deny from all, and connections were refused. So it appears to be a problem wit the variable.

Here's the relevant headers that come in with the request.

Connection: Keep-Alive 
Accept-Encoding: gzip 
CF-Connecting-IP: xx.xx.xx.xx
CF-IPCountry: AU 
X-Forwarded-For: xx.xx.xx.xx.xx
CF-RAY: c9062956e2d04b6 
X-Forwarded-Proto: http 
CF-Visitor: {"scheme":"http"} 
Zone-Name: xx.com.au

Hopefully someone can help me out, this has been driving me nuts for too long.

Thanks

Update

I've now enabled rewrite logging by adding RewriteLogLevel 9 to the virtual host.

Initially I ran the test with all my other htaccess rules which are quite extensive for this site, I could see the various matches all being logged so I know logging was working right.

I stripped my htaccess down to bare bones just to test this case, so I had the following in my htaccess:

SetEnvIf CF-IPCountry AU UnwantedCountry=1
Order allow,deny
Deny from env=UnwantedCountry
Allow from all

With just that in my htaccess, there's no log output at all, which says to me it's simply not matching the rules I'm guessing. I verified again that "CF-IPCountry: AU " is present in the headers.

Best Answer

As an alternative to use SetEnvIf you could do this with a RewriteRule as well.

RewriteCond %{HTTP:CF-IPCountry} ^(AU|SE)$
RewriteRule ^ - [F,L]

This would block AU ans SE users.

Related Topic