Ban IPs from text file using htaccess

徘徊边缘 提交于 2019-12-28 03:50:05

问题


I read and understand how to block an ip using htaccess:

order deny,allow
deny from 111.222.33.44
deny from 55.66.77.88
...
allow from all

But my list of black IPs includes thousands of IPs. I save all IPs to a blacklist.txt file.

Can I use htaccess to call blacklist.txt and block all IPs which are stored in this file? If so, how?


回答1:


You can try using variations of RewriteMap. You'll need access to the server/vhost config because that directive only works there. You can then use the map inside htaccess files.

Say your blacklist.txt file looks like this:

111.222.33.44  deny
55.66.77.88    deny
192.168.0.1    allow

You can define the map like so:

RewriteEngine On
RewriteMap access txt:/path/to/blacklist.txt

Then in your htaccess, you can invoke the map:

RewriteEngine On 
RewriteCond ${access:%{REMOTE_ADDR}} deny [NC]
RewriteRule ^ - [L,F]

The condition invokes the map and checks if the remote address maps to the word "deny", and if so, the rewrite rule outright forbids access.

If your blacklist.txt is only a list of IPs, and you don't want to add a "deny" after each one, you'll need to invoke a program map type and write a script, something like this:

#!/bin/bash

while true
do
    read INPUT
    MATCH=`grep $INPUT /path/to/blacklist.txt`
    if [ -z "$MATCH"  ]; then
        echo "allow"
    else
        echo "deny"
    fi
done

which infinite loops read input and greps the blacklist.txt file. If the IP is in the file, output a "deny", otherwise it outputs a "allow". Then you'd create the map like so:

RewriteEngine On
RewriteMap access prg:/path/to/blacklist.txt

And the rewrite rule to check against the map would be no different.



来源:https://stackoverflow.com/questions/13008242/ban-ips-from-text-file-using-htaccess

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