使用 htaccess 禁止文本文件中的 IP [英] Ban IPs from text file using htaccess

查看:21
本文介绍了使用 htaccess 禁止文本文件中的 IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读并了解如何使用 htaccess 阻止 ip:

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

但我的黑 IP 列表包括数千个 IP.我将所有 IP 保存到 blacklist.txt 文件中.

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

我可以使用 htaccess 调用 blacklist.txt 并阻止存储在此文件中的所有 IP 吗?如果是,怎么办?

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

推荐答案

您可以尝试使用 重写映射.您需要访问服务器/虚拟主机配置,因为该指令仅在那里工作.然后您可以使用 htaccess 文件中的地图.

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.

假设您的 blacklist.txt 文件如下所示:

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

然后在您的 htaccess 中,您可以调用地图:

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.

如果您的 blacklist.txt 只是一个 IP 列表,并且您不想在每个 IP 后添加拒绝",则需要调用程序映射类型并编写一个脚本,像这样:

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

哪个无限循环读取输入并greps blacklist.txt 文件.如果 IP 在文件中,则输出拒绝",否则输出允许".然后你可以像这样创建地图:

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.

这篇关于使用 htaccess 禁止文本文件中的 IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆