【问题标题】:How can I configure Nginx to block specific bots to access the site but allow them to access robots.txt?如何配置 Nginx 以阻止特定机器​​人访问该站点但允许它们访问 robots.txt?
【发布时间】:2018-01-15 08:16:09
【问题描述】:

我有以下 nginx 配置来阻止某些机器人访问基于用户代理的站点。到目前为止它运行良好,但是我发现被阻止的机器人也无法访问 /robots.txt 文件,因此它们每天继续爬取该站点并出现数百个 403 错误。

map $http_user_agent $block_ua {
    default            0;
    ~*yandexbot        1;
}

server {
    # Block bad bots
    if ($block_ua) {
        return 403;
    }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # other location blocks below...
}

我尝试更改配置允许所有bot访问/robots.txt,如下,但是不行,用curl -I -A "yandexbot" [url]测试仍然返回403 Forbidden

server {
    location = /robots.txt {
        try_files $uri $uri/ /index.php?$args;
    }

    # Block bad bots
    if ($block_ua) {
        return 403;
    }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # other location blocks below...
}

我应该在配置中添加什么以获得所需的行为?

【问题讨论】:

    标签: nginx


    【解决方案1】:

    首先,尝试将allow all; 添加到您的 Nginx 配置中。以下示例中的其余部分是可选的:

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }
    

    然后你可以尝试一些类似的东西:

    if ($block_ua) { 
        set $test A; 
    } 
    if ($request_uri = /robots.txt) { 
        set $test B; 
    } 
    if ($test = A) { 
        return 403; 
    }
    

    这是拥有多个 if 语句的一种很老套的方法。见here

    解释

    allow all

    允许访问指定的网络或地址(在本例中为所有)。


    log_not_found off;

    如果文件不存在并且客户端请求它,请不要记录 HTTP 错误 404。


    if ($request_uri = /robots.txt) { set $test A; }

    如果请求的文件不是robots.txt,则将$test设置为“A”


    if ($block_ua){ set $test "${test}B"; }

    如果 UserAgent 匹配,则将 $test 设置为 "$test + B"


    if ($test = AB){ return 403; }

    如果$test 是“AB”,这意味着两个条件都满足,返回403 并阻止机器人。


    其他信息:

    阻止 UserAgent 标头只会阻止 一些 机器人。客户端发送的所有内容都可能被欺骗。包括 UserAgent 字符串。

    【讨论】:

    • 解决方案不起作用,并破坏了站点,“位置〜^ /(?!(机器人\ .txt))”块已抑制其下方的所有位置块,特别是处理php,所以php文件被下载为网站中的文件!
    • @KokHui 查看我的编辑。请让我知道它是否有效
    • 第二个解决方案不起作用,“如果(!-e robots.txt)”似乎总是评估为真,无论我在文件名中输入了什么,例如。 "if (!-e xxx.txt)" 计算结果为真。
    • 我找到了解决方案,使用 $request_uri: if ($block_ua) { set $test A; } if ($request_uri = /robots.txt) { 设置 $test B; } if ($test = A) { 返回 403; }
    • 你能写if (!-e robots\.txt){吗?我很好奇这条线是否被当作正则表达式处理。否则我会编辑答案
    猜你喜欢
    • 2016-08-06
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多