首页 文章

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

提问于
浏览
2

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

我知道处理这个的正确方法是使用RewriteMap,但我不知道如何设置它 .

例如,我希望用户在访问example.com时正常访问我的站点,但是我想拒绝访问访问块路径/目录“http://example.com/block " EXCEPT for those IP addresses in whitelist.txt, additionally, those IP addresses in whitelist.txt will only have access to a specific folder and file inside the " block”目录中任何内容的所有用户,请求例如:

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时,我的网站进入无限重定向循环 .

whitelist.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

... 等等 .

1 回答

  • 0

    我从你的规则开始玩了一下,并得到了这个:

    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
    

    测试时它的工作方式如下:

    希望这可以帮助 .

    EDIT

    • 当在whitelist.txt中找不到IP时,则执行重定向到/ block并使用403代码

    EDIT 2

    目前,来自whitelist.txt文件的任何具有IP的用户都可以访问其他用户目录 . 我真的找不到任何东西 . 所以我现在能想到的是在目录级别拥有 .htaccess 文件,如下所示:

    deny from all
    allow from 1.2.3.4
    #1.2.3.4 is arbitrary
    

相关问题