小知识:Nginx服务器屏蔽与禁止屏蔽网络爬虫的方法

每个网站通常都会遇到很多非搜索引擎的爬虫,这些爬虫大部分都是用于内容采集或是初学者所写,它们和搜索引擎的爬虫不一样,没有频率控制,往往会消耗大量服务器资源,导致带宽白白浪费了。

其实Nginx可以非常容易地根据User-Agent过滤请求,我们只需要在需要URL入口位置通过一个简单的正则表达式就可以过滤不符合要求的爬虫请求:

?
1
2
3
4
5
6
7
location / {
if ($http_user_agent ~* “python|curl|java|wget|httpclient|okhttp”) {
return 503;
}
# 其它正常配置
}

注意:变量$http_user_agent是一个可以直接在location中引用的Nginx变量。~*表示不区分大小写的正则匹配,通过python就可以过滤掉80%的Python爬虫。

Nginx中禁止屏蔽网络爬虫

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
server {
listen    80;
server_name www.xxx.com;
#charset koi8-r;
#access_log logs/host.access.log main;
#location / {
#  root  html;
#  index index.html index.htm;
#}
if ($http_user_agent ~* “qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot”) {
return 403;
}
location ~ ^/(.*)$ {
proxy_pass http://localhost:8080;
proxy_redirect     off;
proxy_set_header    Host $host;
proxy_set_header    X-Real-IP $remote_addr;
proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
client_max_body_size  10m;
client_body_buffer_size 128k;
proxy_connect_timeout  90;
proxy_send_timeout   90;
proxy_read_timeout   90;
proxy_buffer_size    4k;
proxy_buffers      4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
#error_page 404       /404.html;
# redirect server error pages to the static page /50x.html
#
error_page  500 502 503 504 /50x.html;
location = /50x.html {
root  html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#  proxy_pass  http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#  root      html;
#  fastcgi_pass  127.0.0.1:9000;
#  fastcgi_index index.php;
#  fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
#  include    fastcgi_params;
#}
# deny access to .htaccess files, if Apaches document root
# concurs with nginxs one
#
#location ~ /\.ht {
#  deny all;
#}
}

可以用 curl 测试一下

?
1
curl -I -A “qihoobot” www.xxx.com

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:http://www.codetc.com/article-353-1.html

声明: 猿站网有关资源均来自网络搜集与网友提供,任何涉及商业盈利目的的均不得使用,否则产生的一切后果将由您自己承担! 本平台资源仅供个人学习交流、测试使用 所有内容请在下载后24小时内删除,制止非法恶意传播,不对任何下载或转载者造成的危害负任何法律责任!也请大家支持、购置正版! 。本站一律禁止以任何方式发布或转载任何违法的相关信息访客发现请向站长举报,会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。本网站的资源部分来源于网络,如有侵权烦请发送邮件至:2697268773@qq.com进行处理。
建站知识

小知识:Linux C字符串替换函数实例详解

2023-4-10 18:16:36

建站知识

小知识:docker一键安装wordpress的方法步骤

2023-4-10 18:22:14

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索