Apache特定目录和文件的动态IP白名单

我正在尝试动态将 IP 列入白名单以授予对特定目录的访问权限。php 脚本将不断修改白名单.txt文件以添加/删除条目。

我知道处理此问题的正确方法是使用RewriteMap,但我不确定如何设置它。

例如,我希望用户在访问 example.com 时正常访问我的网站,但是我想拒绝所有用户访问块路径/目录“http://example.com/block”中的任何内容,除了白名单中的那些 IP 地址.txt此外,白名单中的那些 IP 地址.txt只能访问“块”目录中的特定文件夹和文件, 请求例如:

http://example.com/block/123/123.txt

我已经尝试了下面的代码(这是一个粗略的草图,我敢肯定它是完全错误的,但只是为了得到这个想法):

RewriteEngine on RewriteCond %{THE_REQUEST} ^\/block+\ ##apply rules only for /block directory RewriteMap ipmap txt://var/whitelist.txt RewriteCond ${ipmap:%{REMOTE_ADDR}} ^\/([0-9]*).txt$ $1 [NC] ##check whitelist for matching IP AND specific dir and file RewriteRule .* - [F,L]

当然,这是行不通的。当我访问 example.com 时,我的网站进入无限重定向循环。

白名单.txt文件如下所示:

170.172.100.162 123 152.109.211.250 43 62.55.254.83 2345 227.202.162.48 32 203.52.248.55 533

因此,IP 地址 170.172.100.162 将可以访问http://www.example.com/block/123/123.txt

IP 地址 152.109.211.250 将有权访问http://www.example.com/block/43/43.txt 等等。

文章译自:https://stackoverflow.com//questions/53690650/apache-dynamic-ip-whitelist-for-specific-directory-and-files
🔜查看未译原文
解决方案:

I’ve played around a bit starting from your rules and got to this:

RewriteEngine On RewriteCond %{THE_REQUEST} \/block\/? # apply rules only for /block directory RewriteMap ipmap txt:/var/whitelist.txt RewriteCond ${ipmap:%{REMOTE_ADDR}} ^$ [NC] RewriteRule .* /block [R=403,L] # redirect to /block with 403 when IP address not in the whitelist RewriteCond %{REQUEST_URI} /+[^\.]+$ [NC] # stops when the request finds a dot '.', assuming a file RewriteCond ${ipmap:%{REMOTE_ADDR}} ^\d+$ [NC] # does the redirect only when the IP is in the whitelist RewriteRule .* /block/${ipmap:%{REMOTE_ADDR}}/${ipmap:%{REMOTE_ADDR}}.txt [R=permanent,L] # will redirect everything from /block to /block/x/x.txt -> x = numeric value corresponding to the request IP from the whitelist.txt file

When tested it worked like this:

Hope this helps.

EDIT:

  • when IP is not found in the whitelist.txt then a redirect to /block with 403 code is performed

EDIT 2:

At the moment any user with an IP from the whitelist.txt file can access other users directory. I’ve tried to find a condition for that but didn’t really find anything. So what I can think of at the moment is having files at directory level like this:.htaccess

deny from all allow from 1.2.3.4 #1.2.3.4 is arbitrary

 

(备注:以上内容转自网络)