Dynamic whitelist with htaccess allowing a form to add an IP to the whitelist?

廉价感情. 提交于 2019-12-07 02:30:42

I recommend using Apache's RewriteMap directive. Please note that to use the RewriteMap directive you have to place the directive in the httpd.conf and NOT the .htaccess file. You can use it in several simple ways.

Plain text file

The plain text version allows you to have a .txt file that holds the ip addresses. I added a line for a comment. This way doesn't allow auto expiration.

httpd.conf

RewriteEngine on
RewriteMap ipmap txt:/path/to/whitelist.txt

RewriteCond ${ipmap:%{REMOTE_ADDR}} !^allow$ [NC]
RewriteRule .* - [F,L]

whitelist.txt

# Chris London added this 2013/06/14
127.0.0.1 allow
123.45.67.89 allow # Some other comment

Custom Program

With the RewriteMap you can actually have it run an external program but this one comes with some caveats. I personally haven't used this method especially with a PHP script. To make it work with a PHP script, I believe, it has to run indefinitely reading the stdin and writing to the stdout.

RewriteEngine on
RewriteLock /path/to/rewrite.lock
Rewritemap ipmap prg:/path/to/executable.php

RewriteCond ${ipmap:%{REMOTE_ADDR}} !^allow$ [NC]
RewriteRule .* - [F,L]

executable.php

#!/usr/bin/php
<?php

$in = fopen('php://stdin', 'r');
$out = fopen('php://stdout', 'r');

while ($ip = fgets($f)) {
    // TODO add better logic
    if ($ip == '127.0.0.1') {
        fwrite(out, 'allow');
    } else {
        fwrite(out, 'deny');
    }
}

fclose($f);
  • Keep your rewrite map program as simple as possible. If the program hangs, it will cause httpd to wait indefinitely for a response from the map, which will, in turn, cause httpd to stop responding to requests.
  • Be sure to turn off buffering in your program. Buffered I/O will cause httpd to wait for the output, and so it will hang.
  • Remember that there is only one copy of the program, started at server startup. All requests will need to go through this one bottleneck. This can cause significant slowdowns if many requests must go through this process, or if the script itself is very slow.

DB Query

I also haven't used this one yet but it looks pretty neat. mod_dbd will need to be configured to point at the right database for this to work. You have a SQL statement that fetchs the ip addresses and you can add a filter for the expiration date.

RewriteEngine on
RewriteMap ipmap "dbd:SELECT ipaddress FROM rewrite WHERE expiration < TIME() and ipaddress = %s"

RewriteCond ${ipmap:%{REMOTE_ADDR}} !^%{REMOTE_ADDR}$ [NC]
RewriteRule .* - [F,L]

There are a couple other types out there but these seem to be the best fit for you. Like I said before I haven't used the Custom Program or the DB Query before so I may have said something wrong. Hopefully another user on here may catch my mistake so these will all work for you.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!