.htaccess dynamic grant access (including system-wide file)

I have a server that hosts several domains and their subdomains, and I'm trying to find the right way to protect some vulnerable folders and subdomains with .htaccess. Everything is fine, but I mean a pretty acceptable solution (programming), but I seem to be unable to get .htaccess to do my evil contests.

Shortly speaking:

  • I have a list of IP addresses stored in a file / database
  • Based on this list, I will generate a file, say /home/ip.allow
  • file contains Allow entries ( Allow from 123.123.123.123 )

In the domains / subdomains that I host on this server, I have simple .htaccess files with the following contents:

 RewriteEngine On Order allow, deny Deny from all 

I am wondering how to enable this /home/ip.allow , so I do not need to programmatically find and edit all .htaccess files in the vhosts path (having all the conditions in only one file, my life is much easier).

I found the RewriteMap directive in the Apache mod_rewrite documentation , but it seems to apply only for rewriting, not for granting access.

Any ideas on this?

+4
source share
1 answer

You can do something like this with mod_rewrite. But you need to change a few things.

Instead of having a file with tons of records that look like this: Allow from 123.123.123.123 you need to create a key / value map so that we can pass it to RewriteMap . In this example, since you specify the set of IP addresses to which you allow access, the file will have many entries that look like this: 123.123.123.123 allow , where "123.123.123.123" is the key and "allow" is the value .

Now we need to install the card for this using RewriteMap , however catch can only be used in the server configuration or in the virtual host configuration, and NOT inside Directory , Files , or the .htaccess file. So you install this somewhere in your httpd.conf or in a virtual host file:

 RewriteMap access_list txt:/home/ip.allow 

Now you can access the access_list in any .htaccess file using a RewriteCond that accesses this map and a RewriteRule that does nothing except question a [F] (Forbidden):

 RewriteCond ${access_list:%{REMOTE_ADDR}} ="" RewriteRule ^(.*)$ - [F,L] 

Here, RewriteCond simply trying to find %{REMOTE_ADDR} as the key to the map file. If there is only 123.123.123.123 allow in your map file, and the remote address is 127.0.0.1 , nothing will match, and the map will return an empty string by executing bit ="" . Otherwise, if the remote address is 123.123.123.123 , then "allow" will be returned and the condition will fail, thus granting access.

You can play with giving or denying depending on how you configured the map file.

+3
source

All Articles