1. 系统与软件更新
定期更新Ubuntu系统和Apache2相关软件包,及时修补已知安全漏洞。执行命令:sudo apt update && sudo apt upgrade,确保所有组件为最新版本。
2. 防火墙配置(UFW)
使用UFW(Uncomplicated Firewall)限制对Apache服务的访问,仅允许必要的HTTP(80/tcp)、HTTPS(443/tcp)流量。操作步骤:sudo ufw allow 'Apache Full'(或分别允许80、443端口),然后启用防火墙:sudo ufw enable。
3. 禁用不必要的Apache模块
禁用不使用的模块(如mod_php、autoindex、mod_autoindex),减少攻击面。通过apache2ctl -M查看已启用模块,禁用时执行:sudo a2dismod 模块名(如sudo a2dismod php7.4),最后重启Apache:sudo systemctl restart apache2。
4. 隐藏敏感信息
修改Apache配置文件,隐藏服务器版本信息和错误详情,防止攻击者利用已知漏洞。编辑/etc/apache2/apache2.conf或/etc/apache2/conf-enabled/security.conf,添加/修改以下指令:ServerTokens Prod(隐藏版本)、ServerSignature Off(关闭错误页签名)。
5. 启用SSL/TLS加密
为网站配置SSL证书,强制使用HTTPS加密数据传输。步骤:① 安装mod_ssl模块:sudo a2enmod ssl;② 创建SSL目录并上传证书(或生成自签名证书):sudo mkdir /etc/apache2/ssl,sudo cp your_cert.crt /etc/apache2/ssl/,sudo cp your_key.key /etc/apache2/ssl/;③ 编辑虚拟主机配置(如/etc/apache2/sites-available/default-ssl.conf),添加SSL指令:SSLEngine on、SSLCertificateFile /etc/apache2/ssl/your_cert.crt、SSLCertificateKeyFile /etc/apache2/ssl/your_key.key;④ 启用SSL站点并重启:sudo a2ensite default-ssl,sudo systemctl restart apache2。
6. 访问控制配置
通过目录权限、IP限制或认证机制限制访问:① 使用<Directory>指令禁止目录列表(Options -Indexes)并设置访问权限(Require all granted或Require ip 192.168.1.1);② 基于IP的访问控制:在<Location>或<Directory>中添加Require ip 允许的IP;③ 基于用户的认证:启用auth_basic模块(sudo a2enmod auth_basic),创建密码文件(sudo htpasswd -c /etc/apache2/.htpasswd 用户名),并在配置中添加AuthType Basic、AuthName "Restricted Area"、AuthUserFile /etc/apache2/.htpasswd、Require valid-user。
7. 安全审计与监控
定期检查Apache日志(访问日志:/var/log/apache2/access.log,错误日志:/var/log/apache2/error.log),及时发现异常行为。可使用工具增强监控:① Fail2Ban:防范暴力破解,安装后配置/etc/fail2ban/jail.local保护SSH和Apache;② Logwatch:自动化日志分析,执行sudo apt install logwatch并配置/etc/logwatch/conf/logwatch.conf。
8. 高级加固措施
① 安装mod_security模块:实时检测并阻止SQL注入、XSS等攻击,执行sudo apt install libapache2-mod-security2,编辑配置文件/etc/apache2/mods-available/security2.conf启用规则;② 使用SELinux或AppArmor:限制Apache进程权限,如AppArmor可通过sudo aa-enforce /etc/apparmor.d/usr.sbin.apache2强制执行。