I am LAZY bones? AN ancient AND boring SITE

2009年 10月 31日 的归档

nginx 禁止某个 User_Agent 的方法

由于ubuntu 9.10 的发布,SRT ubuntu源最近的流量可是飙得厉害~ 昨天一天的平均流量是 9.6MB/s ,算算一天就有800GB了。。。
更可恶的是,一分析日志,有一个“Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”的User_Agent(据说是迅雷的),很是夸张,居然占了八成的流量,看我下面的日志分析:

$ tail -n 1000 /var/log/nginx/mirror.access.log | awk -F\" '{A[$(NF-1)]++}END{for(k in A)print A[k],k}' | sort -n | tail
3 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
4 SAMSUNG-SGH-E250/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 UP.Browser/6.2.3.3.c.1.101 (GUI) MMP/2.0 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)
5 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
6 Ubuntu APT-HTTP/1.3 (0.7.20.2ubuntu6)
16 Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)
18 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
39 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)
41 Ubuntu APT-HTTP/1.3 (0.7.23.1ubuntu2)
94 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; )
767 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)

于是,我不得不想办法禁掉了这个UA,不然也太影响访问了,最近有很多用户都出现访问不畅的状况了。但是网上这方面的资料还真不太好找,于是请教ubuntu-cn的一叶老大,终于找到办法了:
建立一个 /etc/nginx/agent.conf 内容如下(需要注意的是,空格和括弧需要使用“\”进行转义,这也是我摸索了好久得出的结论):

if ($http_user_agent ~ "Mozilla/4.0\ \(compatible;\ MSIE\ 6.0;\ Windows\ NT\ 5.1;\ SV1;\ .NET\ CLR\ 1.1.4322;\ .NET\ CLR\ 2.0.50727\)") { return 404; }

然后在这个site的配置里include这个conf文件,比如 /etc/nginx/sites-enabled/ubuntu-mirror 里添加如下一行: include /etc/nginx/agent.conf;