Premium Member Database last update: Friday, September 30, 2016 22:02:51 GMT-0700

Block Specific IPs From Your Allow List Using SetEnvIf

If you are familiar with .htaccess files you know you can use them to block or allow networks or individual IPs. But did you know you can do both? Let's say you want to allow all networks from the Aland Islands. You could do so by using an .htaccess allow list like so:

<Limit GET POST>
order deny,allow
allow from 79.133.0.0/19
allow from 82.199.160.0/19
allow from 91.187.96.0/19
allow from 194.126.212.0/24
allow from 217.29.224.0/20
deny from all
</Limit>

This will work just fine, but two major improvements can be made to give you more control.

1.) SetEnvIf mod. The SetEnfIf Directive sets environment variables based on attributes of the request.

You can use the SetEnvIf directive to allow you to deny access to specific IP addresses or networks within your allow list. This variable can allow you to fine tune your access control list. Let’s make a few changes to our .htaccess file. We are going to insert the SetEnvIf directive after the <Limit GET POST>. Then we will use the Remote_Addr server variable to grab the visitors IP address and check it against a regular expression to see if it matches. If it does we ban it. We will reverse our order from deny,allow to allow,deny, add our acceptable networks and close the section with a ban on anything matched within the regular expression. Let’s say we want to allow all traffic from the Aland Islands except IP address 79.133.0.17 and 82.199.160.0/24. The command would look like this : SetEnvIf Remote_Addr ^(79\.133\.0\.17|82\.199\.160\.) ban

Putting it all together we have

<Limit GET POST>
order allow,deny
SetEnvIf Remote_Addr ^(79\.133\.0\.17|82\.199\.160\.) ban
allow from 79.133.0.0/19
allow from 82.199.160.0/19
allow from 91.187.96.0/19
allow from 194.126.212.0/24
allow from 217.29.224.0/20
deny from env=ban
</Limit>

2.) Use the LimitExcept directive. The LimitExcept directive restricts access controls to all HTTP methods except the named ones. The only access methods we are going to allow are GET and POST. We place the LimitExcept directly after our closing </Limit> tag. The end result looks like this:

<Limit GET POST>
order allow,deny
SetEnvIf Remote_Addr ^(79\.133\.0\.17|82\.199\.160\.) ban
allow from 79.133.0.0/19
allow from 82.199.160.0/19
allow from 91.187.96.0/19
allow from 194.126.212.0/24
allow from 217.29.224.0/20
deny from env=ban
</Limit>
<LimitExcept GET POST>
Deny from all
</LimitExcept>

You can read more about this in an excellent post on our message board by member Mickey Roush. https://www.countryipblocks.net/cipbb/index.php/topic,130.msg206.html#msg206

Remember, if you become a CIPB - Premium Member you can have instant access to the latest Country Specific Network Data and create your own custom access control lists including custom .htaccess files