使用 Nginx 阻止除少数机器人之外的所有机器人

Posted

技术标签:

【中文标题】使用 Nginx 阻止除少数机器人之外的所有机器人【英文标题】:Blocking all bots except a few with Nginx 【发布时间】:2013-10-20 16:28:04 【问题描述】:

当我输入以下代码时,我想阻止所有标识为机器人但允许 Googlebot 的 http_user_agents:

map $http_user_agent $bad_bot 
default 1;
~*^Lynx 0; # Let Lynx go through
~*^google );
libwww-perl                      1;
~(?i)(libwww|Wget|LWP::Simple|BBBike|java|crawl|spider|bot) 1;

但是,这甚至会阻止对 googlebot 的访问。

【问题讨论】:

【参考方案1】:

只需对照您的 $bad_bot 列表检查 $http_user_agent,如果它在您的黑名单中,则返回 HTTP 403:

location / 
   if ($http_user_agent ~ (libwww|Wget|LWP|damnBot|BBBike|java|spider|crawl) ) 
       return 403;
   

注意: ~ 中的if block 执行区分大小写的匹配。如果您想让您的黑名单不区分大小写,请使用~* 而不是~

【讨论】:

【参考方案2】:

这是我对 nginx 的逻辑

map $http_user_agent $limit_bots 
     default 0;
     ~*(google|bing|yandex|msnbot) 1;
     ~*(AltaVista|Googlebot|Slurp|BlackWidow|Bot|ChinaClaw|Custo|DISCo|Download|Demon|eCatch|EirGrabber|EmailSiphon|EmailWolf|SuperHTTP|Surfbot|WebWhacker) 1;
     ~*(Express|WebPictures|ExtractorPro|EyeNetIE|FlashGet|GetRight|GetWeb!|Go!Zilla|Go-Ahead-Got-It|GrabNet|Grafula|HMView|Go!Zilla|Go-Ahead-Got-It) 1;
     ~*(rafula|HMView|HTTrack|Stripper|Sucker|Indy|InterGET|Ninja|JetCar|Spider|larbin|LeechFTP|Downloader|tool|Navroad|NearSite|NetAnts|tAkeOut|WWWOFFLE) 1;
     ~*(GrabNet|NetSpider|Vampire|NetZIP|Octopus|Offline|PageGrabber|Foto|pavuk|pcBrowser|RealDownload|ReGet|SiteSnagger|SmartDownload|SuperBot|WebSpider) 1;
     ~*(Teleport|VoidEYE|Collector|WebAuto|WebCopier|WebFetch|WebGo|WebLeacher|WebReaper|WebSauger|eXtractor|Quester|WebStripper|WebZIP|Wget|Widow|Zeus) 1;
     ~*(Twengabot|htmlparser|libwww|Python|perl|urllib|scan|Curl|email|PycURL|Pyth|PyQ|WebCollector|WebCopy|webcraw) 1;
  

location / 
  if ($limit_bots = 1) 
    return 403;
  

【讨论】:

人们应该注意,这种方法会禁止谷歌通过捕捉“google”和“bot”这个词来索引你的网站(因为谷歌的http_user_agent中有bot这个词。 @bmiskie 很好的说明,谢谢。就我而言,这正是我想要做的! 有没有办法跳过那些被记录的条目?

以上是关于使用 Nginx 阻止除少数机器人之外的所有机器人的主要内容,如果未能解决你的问题,请参考以下文章

使用 spring SecurityWebFilterChain 如何禁用/阻止除少数已知路径外的所有非 https 请求

使用 :not(selector) 选择除少数之外的所有元素 [重复]

bigquery 按除少数之外的所有列分组

Angularjs:限制对除少数页面之外的所有页面的访问

使 .gitignore 忽略除少数文件之外的所有内容

.htaccess 阻止除我的 ip 之外的所有内容