Nginx -- 如果是referer,将(x-forwarded-for) ip 加入黑名单

Posted

技术标签:

【中文标题】Nginx -- 如果是referer,将(x-forwarded-for) ip 加入黑名单【英文标题】:Nginx -- if referer, add (x-forwarded-for) ip to blacklist 【发布时间】:2020-09-12 22:50:01 【问题描述】:

我编写了一个基本的 http 引用重定向器,看起来像这样:

if ($http_referer ~* (google|yahoo|bing|duckduckgo))   return 301 https://altavista.com; 

我的目标是这样的

if ($http_referer ~* (google|yahoo|bing|duckduckgo)) 
    add $x-forwarded-for bad_ips.txt; <-- this line is the question (x-forwarded-for because it's behind cloudflare)
    return 301 https://altavista.com; 

if ($bad_ip)  
    return 301 https://altavista.com; 

有没有办法做到这一点?目标本质上是,如果您是从黑名单上的网站引荐的,我想将您的 ip 添加到重定向列表中。

注意:这不需要纯粹在 nginx 中完成;使用除了 nginx 之外的其他技术是可以的,只要它们是免费的。

请注意,我的网站正在使用 cloudflare,所以与其禁止一个简单的 IP,不如使用 x-forwarded-for 地址,否则我只是在禁止 cloudflare。

谢谢

【问题讨论】:

为什么不使用fail2ban? easyengine.io/tutorials/nginx/fail2ban 我可以使用fail2ban,但如果可能的话,我真的很想把它链接到上面的指令。 【参考方案1】:

直到我记得没有直接的方法可以做到这一点。

根据this 博客,付费选项可以使用 Nginx Plus。

除此之外,我现在可以看到 2 个选项:

    将OpenResty 与 LUA 模块一起使用。你要做的是

      在每次请求时将 IP 写入文件 对于从文件中读取的每个请求,如果 IP 存在,则 301 重定向。

    如果你不想使用 OpenResty 也可以build Nginx with LUA module。

    [我现在关心的是效率。此方法可能会增加性能开销,因为必须在每个请求上解析文件。]

    在 Nginx 中使用 Fail2Ban。

I wanted to add this in the comment but I don't have enough reputation to comment.

【讨论】:

以上是关于Nginx -- 如果是referer,将(x-forwarded-for) ip 加入黑名单的主要内容,如果未能解决你的问题,请参考以下文章

Nginx防盗链

nginx-modules-reference

nginx 防盗链简单配置

如何阻止 http_referer 与请求的 URL 匹配的 Nginx 请求

NGINX实现图片防盗链(REFERER指令)

nginx的valid_referers指令——防盗链