上周玩客被百度蜘蛛給盯上了,百度蜘蛛對玩客的抓取頻率增加了5倍。百度蜘蛛抓取量驟增,導致服務器負載很高。最終用nginx的ngx_http_limit_req_module模塊限制了百度蜘蛛的抓取頻率。每分鐘允許百度蜘蛛抓取200次,多余的抓取請求返回503。
nginx的配置:
#全局配置
limit_req_zone $anti_spider zone=anti_spider:60m rate=200r/m;
#某個server中
limit_req zone=anti_spider burst=5 nodelay;
if ($http_user_agent ~* “baiduspider”) {
set $anti_spider $http_user_agent;
}
參數說明:
指令linit_req_zone 中的rate=200r/m 表示每分鐘只能處理200個請求。
指令limit_req 中的burst=5 表示最大并發為5。即同一時間只能同時處理5個請求。
指令limit_req 中的 nodelay 表示當已經達到burst值時,再來新請求時,直接返回503
IF部分用于判斷是否是百度蜘蛛的user agent。如果是,就對變量$anti_spider賦值。這樣就做到了只對百度蜘蛛進行限制了。
詳細的參數說明,可以查看官方文檔。
http://nginx.org/en/docs/http/ngx_http_limit_req_module.html#limit_req_zone
這個模塊對請求的限制采用了漏桶算法。
漏桶算法詳見 http://baike.baidu.com/view/2054741.htm
相關代碼請查看nginx源碼文件 src/http/modules/ngx_http_limit_req_module.c
代碼的核心部分是ngx_http_limit_req_lookup 方法。
上一篇:如何打造適合百度抓取的網站
掃一掃 加微信咨詢