nginx根据http_user_agent来拦截访问
原文链接https://blog.csdn.net/qq_22929803/article/details/50724662
1、进入nginx的配置目录,例如cd /usr/local/nginx/conf
2、添加agent_deny.conf配置文件 vim agent_deny.conf
-
#禁止Scrapy等工具的抓取
-
if ($http_user_agent ~* (Scrapy|Curl|HttpClient)) {
-
return 403;
-
}
-
#禁止指定UA及UA为空的访问
-
if ($http_user_agent ~ "FeedDemon|JikeSpider|Indy Library|Alexa Toolbar|AskTbFXTV|AhrefsBot|CrawlDaddy|CoolpadWebkit|Java|Feedly|UniversalFeedParser|ApacheBench|Microsoft URL Control|Swiftbot|ZmEu|oBot|jaunty|Python-urllib|lightDeckReports Bot|YYSpider|DigExt|YisouSpider|HttpClient|MJ12bot|heritrix|EasouSpider|LinkpadBot|Ezooms|^$" )
-
{
-
return 403;
-
}
-
#禁止非GET|HEAD|POST方式的抓取
-
if ($request_method !~ ^(GET|HEAD|POST)$) {
-
return 403;
-
}
还有加一些针对特殊的user_agent的访问
-
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;
-
}
这个是如何得出是频繁访问的user_agent呢,通过分析nginx的日志可以得出
tail -n 1000 /usr/local/nginx/logs/access.log | awk -F\" '{A[$(NF-1)]++}END{for(k in A)print A[k],k}' | sort -n | tail 分析访问次数
执行以上命令可以得出访问最多的user_agent,通过人为判断是否正常来屏蔽
然后在nginx.conf的location中加入include agent_deny.conf;
注意:include agent_deny.conf是放到location下面
平滑重启nginx
/usr/local/nginx/sbin/nginx –s reload
然后测试一下 设置是否成功
curl -I -A "BaiduSpider" www.test.com
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 09 Feb 2015 03:37:20 GMT
Content-Type: text/html; charset=UTF-8 Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.19 Vary: Accept-Encoding, Cookie
Cache-Control: max-age=3, must-revalidate
WP-Super-Cache: Served supercache file from PHP
curl -I -A "JikeSpider" www.test.com
HTTP/1.1 403 Forbidden
Server: nginx Date: Mon, 09 Feb 2015 03:37:44 GMT
Content-Type: text/html
Content-Length: 162 Connection: keep-alive
到这里,nginx通过判断User-Agent屏蔽蜘蛛访问网站就已经完成,可以根据实际情况对agent_deny.conf中的蜘蛛进行增加、删除或者修改。
相关文章
- Nginx -HTTP和反向代理服务器简单配置
- Nginx+Keepalived实现站点高可用
- NGINX Plus 现在完全支持 HTTP/2
- Nginx: ngx_http_geoip_module
- Nginx: ngx_http_geo_module
- Nginx: realip
- nginx基础学习(四):nginx的upstream实现负载均衡
- Nginx状态信息(status)配置及信息详解
- nginx反向代理http与https两种协议配置简述
- Nginx的Permission denied错误
- Nginx降权启动
- nginx模块之ngx_http_proxy_module模块
- 关于直播学习笔记-005 nginx-rtmp、sewiseplayer
- nginx+ssl配置http和https共存
- Nginx的配置文件详解(全局块、events块、http块)
- nginx实现请求的负载均衡 + keepalived实现nginx的高可用
- Nginx主程序使用介绍
- 五、测试nginx配置文件是否正确
- 四、指定Nginx启动用户
- 三、Nginx支持php
- ubuntu系统安装nginx出现的错误(依赖环境没有安装完)
- Nginx配置http请求重定向到https、Nginx防止被域名恶意解析的配置-Nginx 的 default_server 指令
- 浅析Nginx打开目录浏览功能(autoindex)以及alias和root的理解、nginx静态服务访问
- 宝塔配置vue反向代理Nginx解决
- windows下流媒体nginx-rmtp-module服务器搭建及java程序调用fmpeg将rtsp转rtmp直播流【转】
- 中间件:Nginx工作使用记录(反向代理)
- nginx源代码分析--ngx_http_optimize_servers()函数
- Load Balance Tomcat with Nginx and Store Sessions in Redis--reference