Ubuntu Apache实现防盗攻击的综合方案
使用mod_evasive模块限制单个IP在短时间内的高频请求,有效防御DDoS、刷单等攻击。
sudo apt install libapache2-mod-evasive/etc/apache2/mods-enabled/evasive.conf,设置关键参数(可根据业务调整):<IfModule mod_evasive20.c>DOSHashTableSize3097# 哈希表大小,建议保持默认DOSPageCount2 # 单个页面1秒内最多允许2次请求DOSSiteCount50# 整站1秒内最多允许50次请求DOSPageInterval 1 # 页面请求检测时间窗口(秒)DOSSiteInterval 1 # 整站请求检测时间窗口(秒)DOSBlockingPeriod 10# 封禁时间(秒),封禁后IP无法访问</IfModule>sudo a2enmod evasive && sudo systemctl restart apache2通过mod_rewrite模块验证请求来源(Referer),阻止非授权网站盗用图片、视频等静态资源。
sudo a2enmod rewrite && sudo systemctl restart apache2/var/www/html/images)的.htaccess文件中添加:RewriteEngine OnRewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourdomain.com [NC]# 允许自身域名RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?trusted-domain.com [NC]# 可选:允许信任的第三方域名RewriteCond %{HTTP_REFERER} !^$# 允许直接访问(如用户手动输入URL)RewriteRule .(jpg|jpeg|png|gif|svg|webp)$ - [F,L]# 匹配资源扩展名,返回403或在虚拟主机配置(如/etc/apache2/sites-available/your-site.conf)的<Directory>块中添加相同规则通过识别恶意User-Agent或IP,阻止爬虫批量抓取网站内容。
.htaccess或虚拟主机配置中添加:RewriteEngine OnRewriteCond %{HTTP_USER_AGENT} (BadBot|Scrapy|wget|curl) [NC]# 匹配常见恶意爬虫标识RewriteRule .* - [F,L]# 返回403禁止访问<Directory>块中添加:<RequireAll>Require all grantedRequire not ip 192.168.1.100# 封禁单个IPRequire not ip 192.168.1.0/24 # 封禁IP段</RequireAll>sudo apt install libapache2-mod-security2sudo a2enmod security2sudo systemctl restart apache2编辑/etc/modsecurity/modsecurity.conf,添加自定义规则(如封禁访问敏感页面的IP):SecRule REQUEST_URI "@rx /admin|/private" "id:1001,phase:2,deny,status:403,msg:'Blocked suspicious crawler'"重启Apache生效对敏感目录(如后台、数据库管理页面)启用HTTP基本认证,要求用户输入用户名和密码。
sudo htpasswd -c /etc/apache2/.htpasswd admin(首次创建用-c,后续添加用户无需-c).htaccess中添加:<Directory /var/www/html/admin>AuthType BasicAuthName "Restricted Area"AuthUserFile /etc/apache2/.htpasswdRequire valid-user</Directory>重启Apache使配置生效移除Apache响应头中的版本号和系统信息,降低攻击者针对性利用漏洞的风险。
/etc/apache2/conf-enabled/security.conf,设置:ServerTokens Prod# 仅显示"Apache",隐藏版本号ServerSignature Off# 关闭错误页面的服务器信息重启Apache生效通过HTTPS加密传输数据,防止中间人攻击窃取用户信息(如登录密码、支付信息)。
sudo apt install certbot python3-certbot-apachesudo certbot --apache,按提示输入域名,自动配置SSL证书。<VirtualHost *:80>ServerName yourdomain.comRedirect permanent / https://yourdomain.com/</VirtualHost>重启Apache生效通过日志分析和自动化工具,及时发现并响应异常行为。
sudo apt install fail2ban,配置/etc/fail2ban/jail.local添加Apache防护规则:[apache-badbots]enabled = truefilter = apache-badbotsaction = iptables-multiport[name=HTTP, port="http,https", protocol=tcp]logpath = /var/log/apache2/access.logmaxretry = 3bantime = 3600重启fail2ban生效:sudo systemctl restart fail2bantail -f /var/log/apache2/error.log或grep '403' /var/log/apache2/access.log查看异常请求