NGINX 按国家阻止并排除机器人

Posted

技术标签:

【中文标题】NGINX 按国家阻止并排除机器人【英文标题】:NGINX block by country and exclude bots 【发布时间】:2021-05-15 10:02:34 【问题描述】:

我想阻止来自除一个国家/地区以外的所有国家/地区的流量,并将搜索机器人添加到例外情况中。我正在尝试这个:

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country 
   default no;
   RU yes;


server 
   listen 443 ssl http2;
   server_name _default;
   if ($allowed_country = no) 
      set $blocked I;
   
   if ($http_user_agent !~* (google|bing|yandex|msnbot|applebot)) 
      set $blocked G;
   
   if ($blocked = IG)
      return 444;
   
...

但它对我不起作用。

【问题讨论】:

请注意,IP 地理位置不准确。您将禁止部分您不想禁止的用户。 如果你想连接“I”和“G”,第二个set应该是set $blocked "$blockedG"; 【参考方案1】:

感谢@RichardSmith,这是最终代码:

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country 
   default no;
   RU yes;


server 
   listen 443 ssl http2;
   server_name _default;
   if ($allowed_country = no) 
      set $blocked I;
   
   if ($http_user_agent !~* (google|bing|yandex|msnbot|applebot)) 
      set $blocked "$blockedG";
   
   if ($blocked = IG)
      return 444;
   
...

【讨论】:

以上是关于NGINX 按国家阻止并排除机器人的主要内容,如果未能解决你的问题,请参考以下文章