1. 系统与软件更新
定期更新系统和Apache相关软件包是安全基础,可及时修复已知漏洞。执行以下命令更新系统及软件:
sudo apt update && sudo apt upgrade -y
建议开启自动安全更新(如unattended-upgrades),确保系统持续安全。
2. 防火墙配置(UFW)
使用ufw(Uncomplicated Firewall)限制访问,仅开放必要端口(HTTP 80、HTTPS 443),阻止非法流量:
sudo apt install ufw -y
sudo ufw allow 'Apache Full' # 允许HTTP和HTTPS
sudo ufw enable # 启用防火墙
可通过sudo ufw status验证规则是否生效。
3. 隐藏敏感信息(防信息泄露)
修改Apache配置文件,隐藏版本号和服务器标识,降低被针对性攻击的风险:
编辑/etc/apache2/conf-available/security.conf,启用以下指令:
ServerTokens Prod # 仅显示"Apache",不暴露版本
ServerSignature Off # 关闭错误页面中的服务器信息
重启Apache使配置生效:sudo systemctl restart apache2。
4. SSL/TLS加密(数据传输安全)
使用Let’s Encrypt获取免费SSL证书,启用HTTPS加密通信:
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
按提示选择“Redirect to HTTPS”(强制跳转),确保证书自动续期(Certbot会自动配置)。
5. 禁用不必要的模块
Apache默认加载多个模块,禁用不需要的模块可减少攻击面。查看已加载模块:
apache2ctl -M
禁用无用模块(如autoindex、status、userdir):
sudo a2dismod autoindex status userdir
sudo systemctl restart apache2
仅保留必需模块(如ssl、rewrite)。
6. 访问控制(限制IP访问)
通过Directory指令限制敏感目录(如/var/www/html)的访问,仅允许可信IP访问:
编辑虚拟主机配置文件(如/etc/apache2/sites-available/example.com.conf),添加:
<Directory "/var/www/html">
Require ip 192.168.1.0/24 # 允许指定IP段
Require all denied # 拒绝其他所有IP
</Directory>
重启Apache生效。
7. 安全模块配置(增强防护)
安装并配置安全模块,提升服务器抗攻击能力:
sudo apt install libapache2-mod-security2 -y
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
sudo sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/modsecurity/modsecurity.conf # 开启主动防护
sudo a2enmod security2
sudo systemctl restart apache2
sudo apt install libapache2-mod-evasive24 -y
sudo nano /etc/apache2/mods-enabled/evasive24.conf
添加以下规则(调整阈值适应服务器性能):DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 600
重启Apache生效。8. 日志管理与监控
开启详细日志记录,定期检查异常行为:
编辑/etc/apache2/apache2.conf,自定义日志格式和路径:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog ${APACHE_LOG_DIR}/access.log combined
ErrorLog ${APACHE_LOG_DIR}/error.log
使用工具(如tail、GoAccess)实时监控日志:
sudo tail -f /var/log/apache2/access.log
sudo tail -f /var/log/apache2/error.log
定期归档日志(如按天分割),避免日志文件过大。
9. PHP安全配置(若使用PHP)
若运行PHP应用,需调整php.ini增强安全性:
sudo nano /etc/php/8.2/apache2/php.ini # 根据PHP版本调整路径
修改以下关键参数:
expose_php = Off # 隐藏PHP版本
disable_functions = exec,system,shell_exec,passthru # 禁用危险函数
log_errors = On # 开启错误日志
error_log = /var/log/php_errors.log # 指定错误日志路径
重启Apache使配置生效。
10. 定期备份与维护
定期备份配置文件和网站数据,防止数据丢失:
sudo cp -R /etc/apache2 /etc/apache2-backup
sudo cp -R /var/www/html /var/www/html-backup
建议使用自动化工具(如rsync、BorgBackup)定期备份,并将备份存储在异地。