Ubuntu Apache实现防盗攻击的综合方案
使用mod_evasive模块限制单个IP在短时间内的高频请求,有效防御DDoS、刷单等攻击。
sudo apt install libapache2-mod-evasive/etc/apache2/mods-enabled/evasive.conf,设置关键参数(可根据业务调整):<IfModule mod_evasive20.c> DOSHashTableSize 3097 # 哈希表大小,建议保持默认 DOSPageCount 2 # 单个页面1秒内最多允许2次请求 DOSSiteCount 50 # 整站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 On RewriteCond %{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 On RewriteCond %{HTTP_USER_AGENT} (BadBot|Scrapy|wget|curl) [NC] # 匹配常见恶意爬虫标识 RewriteRule .* - [F,L] # 返回403禁止访问 <Directory>块中添加:<RequireAll> Require all granted Require not ip 192.168.1.100 # 封禁单个IP Require not ip 192.168.1.0/24 # 封禁IP段 </RequireAll> sudo apt install libapache2-mod-security2 sudo a2enmod security2 sudo 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 Basic AuthName "Restricted Area" AuthUserFile /etc/apache2/.htpasswd Require 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.com Redirect permanent / https://yourdomain.com/ </VirtualHost> 重启Apache生效通过日志分析和自动化工具,及时发现并响应异常行为。
sudo apt install fail2ban,配置/etc/fail2ban/jail.local添加Apache防护规则:[apache-badbots] enabled = true filter = apache-badbots action = iptables-multiport[name=HTTP, port="http,https", protocol=tcp] logpath = /var/log/apache2/access.log maxretry = 3 bantime = 3600 重启fail2ban生效:sudo systemctl restart fail2bantail -f /var/log/apache2/error.log或grep '403' /var/log/apache2/access.log查看异常请求