.htaccess dynamic grant access (include system-wide file)
I have a server hosting several domains and their subdomains and I'm trying to find the right way to protect some sensitive folders and subdomains using .htaccess. All good for now, but I have in mind a pretty doable solution (programming-wise) but I can't seem to get .htaccess to do my evil biddings.
Long story short:
- I have a list of IPs stored in a file/database
- based on this list I generate a file, let's say
/home/ip.allow
- the file contains
Allow
entries (Allow from 123.123.123.123
)
In the domains/subdomains I host on this server I have simple .htaccess files with the following content:
RewriteEngine On
Order allow, deny
Deny from all
The thing I'm interested in is how do I include that /home/ip.allow
so I don't have to programmatically find and edit all the .htaccess files in the vhosts path (having all the conditions in only one file would make my life so much easier).
I did find the RewriteMap
开发者_运维知识库 directive in the Apache's mod_rewrite documentation but that seems to apply only for rewrites, not for granting access.
Any ideas on this subject?
You can do something similar using mod_rewrite. But you'll need to change a few things around.
Instead of having a file with a ton of entries that look like this: Allow from 123.123.123.123
you'll need to create a key/value map so we can pass it to RewriteMap. In this example, since you are listing a set of IPs that you will allow access to, the file will have a bunch of 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 have to setup a map for this by using RewriteMap
, however, the catch is we can only use it in the server config or a virtual host config, and NOT inside a Directory
, Files
, or the .htaccess file. So you set this up somewhere in your httpd.conf or your virtual host file:
RewriteMap access_list txt:/home/ip.allow
Now you can access the map access_list
in any .htaccess file by using a RewriteCond that accesses this map and a RewriteRule
that does nothing except issue a [F]
(Forbidden):
RewriteCond ${access_list:%{REMOTE_ADDR}} =""
RewriteRule ^(.*)$ - [F,L]
The RewriteCond
here just tries to find the %{REMOTE_ADDR}
as a key to the map file. If the only thing in your map file is 123.123.123.123 allow
and the remote address is 127.0.0.1
, nothing will match and the map will return an empty string, thus fulfilling the =""
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 around with granting or denying depending on how you've setup the map file.
精彩评论