温馨提示×

Ubuntu Apache配置如何优化安全性

小樊
38
2025-11-01 01:34:58
栏目: 智能运维

1. 系统与软件更新
定期更新Ubuntu系统和Apache软件包,及时修复已知安全漏洞。执行以下命令更新系统及软件:

sudo apt update && sudo apt upgrade -y

2. 防火墙配置(UFW)
使用UFW限制对Apache服务端口的访问,仅允许必要的HTTP(80)和HTTPS(443)流量:

sudo apt install ufw -y
sudo ufw allow 'Apache Full'  # 允许HTTP和HTTPS
sudo ufw enable               # 启用防火墙
sudo ufw status               # 验证规则(应显示ALLOW 80/tcp、ALLOW 443/tcp)

3. 禁用未使用的Apache模块
禁用不需要的模块以减少攻击面。常见可禁用模块包括userdir(用户目录访问)、autoindex(目录列表)、status(服务器状态)、cgi(CGI脚本)等:

sudo a2dismod userdir autoindex status cgi  # 禁用指定模块
sudo systemctl restart apache2              # 重启Apache使更改生效

4. 隐藏Apache敏感信息
修改Apache配置文件,隐藏版本号和操作系统信息,防止攻击者利用已知漏洞针对性攻击:

sudo nano /etc/apache2/conf-enabled/security.conf
# 修改以下两行(若不存在则添加)
ServerTokens Prod    # 仅显示"Apache",不暴露版本
ServerSignature Off  # 关闭错误页面中的服务器信息
sudo systemctl restart apache2

5. 启用SSL/TLS加密(HTTPS)
使用Certbot为Apache配置免费SSL证书,强制HTTPS访问,加密数据传输:

sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com  # 替换为你的域名
# 按提示完成证书申请(自动配置Apache虚拟主机)

6. 限制访问权限
通过文件系统权限和Apache配置,限制对网站根目录及敏感文件的访问:

# 设置网站根目录权限(www-data为Apache默认用户)
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html

# 禁止目录列表(针对敏感目录,如/var/www/html/uploads)
sudo nano /etc/apache2/apache2.conf
<Directory /var/www/html/uploads>
    Options -Indexes  # 关闭目录列表
    Require all denied  # 拒绝所有访问(需根据需求调整)
</Directory>
sudo systemctl restart apache2

7. 配置日志审计与监控
启用Apache访问日志和错误日志,定期监控异常活动(如大量404错误、可疑IP访问):

# 日志路径(默认)
AccessLog ${APACHE_LOG_DIR}/access.log
ErrorLog ${APACHE_LOG_DIR}/error.log

# 使用fail2ban监控并阻止恶意IP
sudo apt install fail2ban -y
sudo cp /etc/fail2ban/jail.local /etc/fail2ban/jail.local.bak  # 备份默认配置
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
# 查看fail2ban状态:sudo fail2ban-client status

8. 使用安全模块增强防护
启用ModSecurity等安全模块,对HTTP请求进行实时过滤,防止SQL注入、跨站脚本(XSS)等攻击:

sudo apt install libapache2-mod-security2 -y
sudo a2enmod security2
# 配置ModSecurity规则(示例:启用OWASP核心规则集)
sudo mkdir /etc/apache2/modsecurity.d
sudo wget https://github.com/coreruleset/coreruleset/archive/v3.4.0.tar.gz -O /tmp/crs.tar.gz
sudo tar -xzf /tmp/crs.tar.gz -C /etc/apache2/modsecurity.d/ --strip-components=1
sudo nano /etc/apache2/modsecurity.d/owasp-modsecurity-crs/crs-setup.conf
# 根据需求调整规则(如启用/禁用特定规则)
sudo systemctl restart apache2

9. 禁用目录浏览
关闭Apache的目录浏览功能,防止敏感文件(如.gitconfig.php)泄露:

sudo nano /etc/apache2/apache2.conf
<Directory /var/www/html>
    Options -Indexes  # 关闭目录列表
</Directory>
sudo systemctl restart apache2

10. 强化SSH访问(间接提升Apache安全性)
通过SSH密钥认证替代密码认证,修改默认端口,禁用root登录,减少服务器被入侵的风险:

# 生成SSH密钥对(本地机器执行)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
ssh-copy-id user@your_server_ip  # 将公钥复制到服务器

# 修改SSH配置(服务器执行)
sudo nano /etc/ssh/sshd_config
# 修改以下参数
Port 2222                # 修改默认端口(如2222)
PermitRootLogin no       # 禁用root登录
PasswordAuthentication no # 禁用密码认证
PubkeyAuthentication yes  # 启用密钥认证
sudo systemctl restart sshd

0