在Apache中配置防盗爬虫可以通过多种方式实现,以下是一些常见的方法:
mod_rewrite
模块启用mod_rewrite
模块:
确保你的Apache服务器已经启用了mod_rewrite
模块。你可以在httpd.conf
或apache2.conf
文件中找到并取消注释以下行:
LoadModule rewrite_module modules/mod_rewrite.so
创建或编辑.htaccess
文件:
在你的网站根目录下创建或编辑.htaccess
文件,并添加以下内容:
RewriteEngine On
# 检查Referer头
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule .* - [F,L]
这段代码会检查所有请求的Referer
头,如果Referer
不是来自你的域名,则返回403 Forbidden状态码。
mod_security
模块安装mod_security
模块:
如果你还没有安装mod_security
,可以使用以下命令进行安装:
sudo apt-get install libapache2-mod-security2 # Debian/Ubuntu
sudo yum install mod_security # CentOS/RHEL
配置mod_security
规则:
编辑/etc/modsecurity/modsecurity.conf
或/etc/apache2/conf-available/security2.conf
文件,添加以下规则:
SecRule REQUEST_URI "@rx \.(jpg|jpeg|png|gif|ico|css|js)$" \
"id:1000001,\
phase:2,\
deny,\
status:403,\
log,\
msg:'Access to static resources is blocked'"
这段代码会阻止对静态资源的直接访问。
mod_evasive
模块安装mod_evasive
模块:
如果你还没有安装mod_evasive
,可以使用以下命令进行安装:
sudo apt-get install libapache2-mod-evasive # Debian/Ubuntu
sudo yum install mod_evasive # CentOS/RHEL
配置mod_evasive
规则:
编辑/etc/apache2/mods-enabled/evasive.conf
或/etc/httpd/conf.d/evasive.conf
文件,添加以下配置:
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10
</IfModule>
这段代码会检测并阻止恶意请求。
你也可以编写自定义脚本来检测和阻止爬虫。例如,你可以使用PHP编写一个简单的脚本来检查请求头并返回403状态码:
<?php
if (!empty($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'yourdomain.com') === false) {
header('HTTP/1.1 403 Forbidden');
exit;
}
// 继续处理请求
?>
将这个脚本放在你的网站根目录下,并在.htaccess
文件中添加以下行:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /block-crawler.php [L]
mod_security
和mod_evasive
。通过以上方法,你可以有效地在Apache中配置防盗爬虫,保护你的网站免受恶意爬虫的侵害。