Ubuntu中Apache的安全设置指南
sudo apt update && sudo apt upgrade,确保系统和Apache及其依赖库为最新版本,修补已知安全漏洞。sudo apt install apache2安装Apache;启用SSL(sudo a2enmod ssl)、HTTP头(sudo a2enmod headers)、重写(sudo a2enmod rewrite)等核心模块,增强基础安全能力。sudo ufw allow 'Apache Full'(允许HTTP 80端口和HTTPS 443端口),然后启用防火墙sudo ufw enable,阻止非法IP访问Web服务。/etc/apache2/apache2.conf或/etc/apache2/conf-enabled/security.conf),设置ServerTokens Prod(隐藏操作系统和Apache版本)和ServerSignature Off(禁用错误页面的服务器信息),减少攻击者利用版本漏洞的机会。<Directory>块(如/var/www/html)中添加Options -Indexes,防止当目录无index.html时自动列出文件,避免敏感文件泄露。sudo a2dismod 模块名(如php7.x_module、status_module等),禁用不需要的模块,减少攻击面。禁用前可通过apache2ctl -M查看已启用模块。sudo apt install certbot python3-certbot-apache,然后执行sudo certbot --apache -d yourdomain.com -d www.yourdomain.com,自动配置HTTPS。确保证书路径正确(如/etc/apache2/ssl/),并重启Apache使配置生效。<Directory>块中使用Require ip指令,如<Directory "/var/www/html/restricted"> Require ip 192.168.1.1 192.168.1.2 </Directory>,仅允许指定IP访问敏感目录;或使用.htaccess文件(需启用AllowOverride All)实现相同功能。sudo htpasswd -c /etc/apache2/.htpasswd 用户名创建用户,然后在配置文件中添加AuthType Basic、AuthName "Restricted Area"、AuthUserFile /etc/apache2/.htpasswd和Require valid-user指令,要求用户输入凭证才能访问。sudo apt install libapache2-mod-security2,启用模块sudo a2enmod security2,编辑/etc/apache2/conf-available/security2.conf,设置SecRuleEngine On(开启规则引擎),并包含OWASP CRS规则集(Include /etc/apache2/conf-available/crs-setup.conf),防范SQL注入、XSS等攻击。sudo apt install libapache2-mod-evasive20,编辑/etc/apache2/mods-enabled/evasive.conf,调整参数(如DOSPageCount 2(每秒2次相同请求触发)、DOSBlockingPeriod 10(阻断10秒)),限制高频请求,防止DoS/DDoS攻击。/etc/apache2/apache2.conf中设置LogLevel warn(记录警告及以上级别日志),ErrorLog ${APACHE_LOG_DIR}/error.log(错误日志路径),CustomLog ${APACHE_LOG_DIR}/access.log combined(访问日志格式),便于后续分析异常行为。fail2ban防范暴力破解,运行sudo apt install fail2ban,复制配置文件sudo cp /etc/fail2ban/jail.local /etc/fail2ban/jail.local.bak,编辑jail.local启用Apache日志监控(如[apache-auth]部分),设置enabled = true,并启动服务sudo systemctl start fail2ban;定期使用logwatch(sudo apt install logwatch)生成日志报告,分析访问趋势。sudo apt install apparmor apparmor-utils,编辑Apache配置文件/etc/apparmor.d/usr.sbin.apache2,添加所需权限(如访问/var/www/html),然后执行sudo aa-enforce /etc/apparmor.d/usr.sbin.apache2,限制Apache进程的权限,防止越权操作。/etc/apache2)和网站数据(/var/www/html),使用tar命令(如sudo tar -czvf /backup/apache_backup_$(date +%Y%m%d).tar.gz /etc/apache2 /var/www/html),存储到远程服务器或云存储,确保数据丢失后可快速恢复。