通过Apache配置实现防盗爬虫,可以采用以下几种方法:
mod_rewrite
模块mod_rewrite
模块可以用来重写URL,从而阻止或限制对特定资源的访问。
RewriteEngine On
# 阻止特定IP访问
RewriteCond %{REMOTE_ADDR} ^123\.456\.789\.0$
RewriteRule .* - [F]
# 阻止特定User-Agent访问
RewriteCond %{HTTP_USER_AGENT} ^BadBot$
RewriteRule .* - [F]
# 限制访问频率
RewriteCond %{REQUEST_URI} ^/sensitive-page$
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.0$
RewriteCond %{REQUEST_URI} !^/whitelist-page$
RewriteCond %{REQUEST_URI} !^/robots.txt$
RewriteCond %{REQUEST_URI} !^/favicon\.ico$
RewriteCond %{REQUEST_URI} !^/api/.*$
RewriteCond %{REQUEST_URI} !^/static/.*
RewriteRule .* - [F,L]
mod_security
模块mod_security
是一个强大的Web应用防火墙(WAF),可以用来检测和阻止恶意请求。
LoadModule security2_module modules/mod_security2.so
<IfModule security2_module>
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess On
# 阻止特定IP访问
SecRule REMOTE_ADDR "@ipMatch 123.456.789.0" "id:1000001,deny,status:403"
# 阻止特定User-Agent访问
SecRule REQUEST_HEADERS:User-Agent "@pm BadBot" "id:1000002,deny,status:403"
# 限制访问频率
SecRule REQUEST_URI "@rx ^/sensitive-page$" "id:1000003,phase:2,t:none,limitreq:10/sec,block"
</IfModule>
mod_evasive
模块mod_evasive
模块可以用来检测和阻止恶意请求,特别是DDoS攻击。
LoadModule evasive20_module modules/mod_evasive20.so
<IfModule evasive20_module>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10
</IfModule>
mod_authz_core
模块mod_authz_core
模块可以用来基于IP地址、User-Agent等进行访问控制。
<Directory "/var/www/html">
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd
Require ip 123.456.789.0
Require not user BadBot
</Directory>
mod_headers
模块mod_headers
模块可以用来修改HTTP响应头,从而阻止爬虫。
<IfModule mod_headers.c>
Header set X-Robots-Tag "noindex, nofollow" env=bad_bot
SetEnvIf User-Agent "BadBot" bad_bot
</IfModule>
通过以上方法,可以有效地防止爬虫对网站的恶意访问和数据抓取。