在Ubuntu上安全设置Apache2涉及多个步骤,包括安装、配置、更新、禁用不必要的服务和模块、以及加强访问控制。以下是一个详细的指南:
首先,确保你的系统是最新的,并安装Apache2:
sudo apt update
sudo apt upgrade
sudo apt install apache2
配置监听端口:
编辑 /etc/apache2/ports.conf
文件,确保Apache监听在安全的端口上(例如80和443)。
Listen 80
Listen 443
配置虚拟主机:
编辑 /etc/apache2/sites-available/000-default.conf
文件,设置虚拟主机。
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
禁用不必要的模块:
编辑 /etc/apache2/mods-enabled/dir.conf
,关闭不需要的模块。
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
启用SSL/TLS:
安装 mod_ssl
模块并配置SSL证书。
sudo apt install libapache2-mod-ssl-stapling
sudo mkdir /etc/apache2/ssl/
sudo openssl req -new -x509 -days 365 -nodes -out /etc/apache2/ssl/apache.crt -keyout /etc/apache2/ssl/apache.key
编辑 /etc/apache2/sites-available/default-ssl.conf
文件。
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key
</VirtualHost>
隐藏敏感信息:
修改 /etc/apache2/conf-enabled/security.conf
文件,隐藏Apache的版本信息和签名。
ServerTokens Prod
ServerSignature Off
禁止目录列表:
在虚拟主机配置文件中,禁用目录列表。
Options -Indexes
配置防火墙:
使用 ufw
允许HTTP和HTTPS流量。
sudo ufw allow 'Apache Full'
设置Apache以特定用户和组运行:
编辑 /etc/apache2/envvars
文件,设置Apache运行的用户和组。
export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data
定期更新:
定期更新Apache和相关模块,以修补安全漏洞。
sudo apt update
sudo apt upgrade
禁用不必要的Apache模块:
通过 a2dismod
命令禁用不需要的模块。
sudo a2dismod module_name
防止DDoS攻击:
安装并配置 mod_evasive
模块。
sudo apt install libapache2-mod-evasive
防止Slowloris攻击:
安装并配置 mod_qos
模块。
sudo apt install libapache2-mod-qos
防止DNS注入攻击:
安装并配置 mod_spamhaus
模块。
sudo apt install libapache2-mod-spamhaus
通过以上步骤,你可以显著提高Ubuntu上Apache2服务器的安全性。