在Ubuntu上配置Apache2以防止防盗刷,通常涉及以下几个方面:
mod_evasive
模块来限制单个IP地址在一定时间内的请求数量。以下是具体步骤:
mod_evasive
mod_evasive
是一个用于防止DDoS攻击和防盗刷的模块。
mod_evasive
sudo apt-get update
sudo apt-get install libapache2-mod-evasive
mod_evasive
编辑/etc/apache2/mods-enabled/evasive.conf
文件(如果不存在,可以创建一个):
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10
</IfModule>
DOSHashTableSize
:哈希表的大小。DOSPageCount
:单个页面在指定时间内的最大请求数。DOSSiteCount
:单个网站在指定时间内的最大请求数。DOSPageInterval
:页面请求的时间间隔(秒)。DOSSiteInterval
:网站请求的时间间隔(秒)。DOSBlockingPeriod
:被封禁的时间(秒)。sudo a2enmod evasive
sudo systemctl restart apache2
你可以为敏感目录或文件设置HTTP基本认证。
sudo htpasswd -c /etc/apache2/.htpasswd username
按照提示输入密码。-c
选项表示创建新文件,如果文件已存在,可以去掉-c
选项。
编辑/etc/apache2/sites-available/your-site.conf
文件,添加以下内容:
<Directory /var/www/html/protected>
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
启用站点并重启Apache:
sudo a2ensite your-site.conf
sudo systemctl restart apache2
你可以使用第三方库如reCAPTCHA
来添加验证码。
libapache2-mod-php7.4
(如果尚未安装)sudo apt-get install libapache2-mod-php7.4
编辑/etc/php/7.4/apache2/php.ini
文件,确保以下行未被注释:
extension=curl
extension=gd
重启Apache:
sudo systemctl restart apache2
在你的HTML表单中添加reCAPTCHA
:
<form action="submit_form.php" method="post">
<!-- 其他表单字段 -->
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
在submit_form.php
中验证验证码:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR_SECRET_KEY&response=" . $_POST['g-recaptcha-response']);
$responseData = json_decode($response);
if ($responseData->success) {
// 验证码正确,处理表单数据
} else {
// 验证码错误,显示错误信息
echo "Invalid CAPTCHA.";
}
}
?>
定期检查Apache日志文件,发现异常行为:
sudo tail -f /var/log/apache2/access.log
sudo tail -f /var/log/apache2/error.log
你可以使用工具如fail2ban
来自动封禁恶意IP地址。
fail2ban
sudo apt-get install fail2ban
fail2ban
编辑/etc/fail2ban/jail.local
文件,添加以下内容:
[DEFAULT]
bantime = 600
findtime = 600
maxretry = 3
[apache-auth]
enabled = true
filter = apache-auth
action = iptables-multiport[name=Apache, port="http,https", protocol=tcp]
logpath = /var/log/apache2/access.log
重启fail2ban
:
sudo systemctl restart fail2ban
通过以上步骤,你可以在Ubuntu上配置Apache2以防止防盗刷。