Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In my Apache config I want to set an environment variable if I see that the visitor comes from an specific IP range. Currently I do it this way:

SetEnvIfNoCase Remote_Addr "^194\.8\.7[45]\." banned=spammer-ip
SetEnvIfNoCase Remote_Addr "^212\.156\.170\." banned=spammer-ip

What I would prefer is something like this:

SetEnvIfIpRange banned=spammer-ip
SetEnvIfIpRange banned=spammer-ip

... because I think that converting an IP address to a string and then do an regular expression is a total waste of ressources.

I could do an

Deny From

... but then I don't get a variable that I can check in my 403 error page - to find the reason why access has been denied.

Any suggestions what I might miss? Is there an Apache2 MOD that can set environment variables based on "IP Address Ranges"?

share|improve this question
up vote 2 down vote accepted

What you've got (SetEnvIfNoCase Remote_Addr "^a.b.c." env_key=env_value) is the best you'll easily do. I've seen this configuration style implemented on a heavily loaded cluster of machines, without any noticeable performance degradation. I agree using regular expressions, when CIDR ranges are more appropriate is annoying. You could write a small program to automatically generate the config from a list of CIDR ranges.

If you're familiar with Perl, you could create a modperl handler, which would allow/deny requests in whichever way you choose. modperl allows your code to run at different points throughout a HTTP request - mod_perl 2.0 HTTP Request Cycle Phases. PerlAuthzHandler would be the appropriate handler to use.


share|improve this answer

You may use CIDR formatting with Apache 2.4 which allows <If>:

<If "%{REMOTE_ADDR} -ipmatch">
    SetEnv banned = spammer-ip
share|improve this answer
Thanks your answer ! Note that there was a bug in my Apache version, so that I had to enclose the IP range in single quotes:… – Lucas Cimon Aug 28 '15 at 9:52

be aware that variables set through SetEnv are not visible on some operations (see matrix):

your solution is

SetEnvIfExpr "-R '' || -R '' || -R ''" rfc1918


share|improve this answer

This is not really a solution to go from RegExp to IP Ranges, but I found a nice script hosted by Google to convert an IP range to a matching regexp. Could be of use for some of you, too...

How do I exclude traffic from a range of IP addresses?


It looks as if Google has removed the IP Address Tool (or at least the link they have on their site is broken), but there is a similar tool here:

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.