保护 Ubuntu 上的 Apache2 是一个系统性工作,下面按从基础到进阶给你一份实用清单,适合生产环境。
sudo apt update
sudo apt upgrade -y
定期更新:
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
防止泄露版本号:
sudo nano /etc/apache2/conf-available/security.conf
修改:
ServerTokens Prod
ServerSignature Off
启用并重启:
sudo a2enconf security
sudo systemctl restart apache2
<Directory /var/www/html>
Options -Indexes
</Directory>
<Directory /var/www/html/admin>
Require ip 1.2.3.4
</Directory>
sudo chown -R www-data:www-data /var/www/html
sudo find /var/www/html -type d -exec chmod 755 {} \;
sudo find /var/www/html -type f -exec chmod 644 {} \;
⚠️ 不要给 web 目录 777 权限
Ubuntu 默认已使用:
ps aux | grep apache2
确认是 www-data 用户。
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache
自动续期测试:
sudo certbot renew --dry-run
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
sudo ufw allow OpenSSH
sudo ufw allow 'Apache Full'
sudo ufw enable
检查:
sudo ufw status
sudo nano /etc/apache2/ports.conf
通常只需:
Listen 80
Listen 443
Header always append X-Frame-Options SAMEORIGIN
启用 headers 模块:
sudo a2enmod headers
Header set X-Content-Type-Options "nosniff"
Header set X-XSS-Protection "1; mode=block"
/var/log/apache2/access.log
/var/log/apache2/error.log
建议安装:
sudo apt install goaccess
goaccess /var/log/apache2/access.log -c
sudo apt install fail2ban
Apache 规则示例:
[apache-auth]
enabled = true
sudo a2dismod autoindex cgi
查看已启用的模块:
apache2ctl -M
LimitRequestBody 1048576
✅ 使用 Nginx + Apache(反向代理)
✅ 使用 AppArmor / SELinux
✅ 定期备份 /var/www 和数据库
✅ 使用 Web 应用防火墙(如 ModSecurity)
如果你愿意,我可以:
你可以直接贴出你的 Apache 虚拟主机配置。