Ban Origin IPs in .htaccess


I have researched all the published advice on the topic, but so far nothing seems to work. I want to ban IPs in .htaccess. But I am on a shared server without mod_cloudflare. I need to be able to access the origin IPs rather than the proxy ones.

This was my best effort, but it didn’t work:

SetEnvIf HTTP_CF_CONNECTING_IP (^456.456.456.456) bad_bot
Require all Granted
Require not env bad_bot

I don’t have any trouble getting the CF_CONNECTING_IP in php, but I would rather use .htaccess.

Something wrong with the syntax? Any other ideas?


Have you tried

SetEnvIf CF-Connecting-IP ^123\.123\.123\.123$ bad_bot


Thanks, @sandro
I believe I did, but I’ll try again and report back.

The reason for the parentheses is that I want to be able to do something like this as well:
SetEnvIf HTTP_CF_CONNECTING_IP (^|^345.345.345.345) bad_bot

Also, the $ creates a problem with IPs of the form 678.678 or 678.678.678


The parentheses are not exactly the issue. I would assume it is the specified attribute.


Way to go, @sandro! I thought I tried every variation, but yours worked.

In fact, all of these work:
SetEnvIf CF-Connecting-IP ^$ bad_bot
SetEnvIf CF-Connecting-IP ^ bad_bot
SetEnvIf CF-Connecting-IP ^(|456.456.456) bad_bot

But, notably, these do not:
SetEnvIf CF_CONNECTING_IP ^(|456.456.456) bad_bot
SetEnvIfNoCase CF_CONNECTING_IP ^(|456.456.456) bad_bot

I didn’t think the server variable was case-sensitive, especially considering on my shared server phpinfo() reports it as HTTP_CF_CONNECTING_IP. But it is.

I guess that’s why you’re an MVP. :smile:


So, now I have a related problem. I want to access the same variable in a RewriteCond, checking for a filename that matches the visitor’s origin IP. But these don’t work:

RewriteCond %{DOCUMENT_ROOT}/deny/%{CF_CONNECTING_IP} -f
RewriteCond %{DOCUMENT_ROOT}/deny/%{CF-Connecting-IP} -f

The part after /deny/ is always empty. What is the correct way to specify the variable?

RewriteCond %{DOCUMENT_ROOT}/deny/%{HTTP:CF-Connecting-IP} -f

Though to be honest, these questions would better fit in an Apache specific forum and it is actually quite well documented at :wink:


Thank you, Sandro, for answering the question, even though it is well documented elsewhere. I sense that future Cloudflare users may have the same trouble I did and will likely find this result first in their searches. :wink: