温馨提示×

CentOS如何保护Apache

小樊
36
2026-07-08 17:52:40
栏目: 智能运维

在 CentOS 上保护 Apache(httpd)主要从系统层面、Apache 配置层面、网络层面和应用层面四个方向入手。下面给你一套实用且可落地的加固方案,适用于 CentOS 7 / 8 / Stream。


一、系统层面加固

1. 保持系统和软件更新

yum update -y

或(CentOS 8 / Stream):

dnf update -y

2. 最小安装原则

  • 只安装必要模块
  • 删除测试页面
rm -f /var/www/html/index.html

3. 使用非 root 用户运行 Apache

CentOS 默认已使用 apache 用户,确认:

ps aux | grep httpd

二、Apache 配置加固

1. 隐藏版本信息(非常重要)

编辑:

vim /etc/httpd/conf/httpd.conf

添加或修改:

ServerTokens Prod
ServerSignature Off

重启:

systemctl restart httpd

2. 禁用目录浏览

防止泄露目录结构:

<Directory /var/www/html>
    Options -Indexes
</Directory>

3. 禁用不必要的 HTTP 方法

只允许 GET / POST:

<Location />
    AllowMethods GET POST
</Location>

4. 限制访问敏感目录

<Directory /var/www/html/admin>
    Order Deny,Allow
    Deny from all
    Allow from 192.168.1.0/24
</Directory>

或使用新语法:

<Directory /var/www/html/admin>
    Require all denied
    Require ip 192.168.1.0/24
</Directory>

5. 防止访问 .git / .env 等文件

<FilesMatch "^\.(git|env|log|sql|conf)$">
    Require all denied
</FilesMatch>

三、使用防火墙和 SELinux(强烈推荐)

1. 防火墙(firewalld)

systemctl enable firewalld
systemctl start firewalld

firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

只开放必要端口(80 / 443)


2. SELinux(CentOS 一大安全优势)

✅ 不要关闭 SELinux
检查状态:

getenforce

配置 Apache 访问规则:

setsebool -P httpd_can_network_connect 1

如需上传目录:

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/uploads(/.*)?"
restorecon -Rv /var/www/html/uploads

四、HTTPS 加密(必须)

1. 安装证书

可使用 Let’s Encrypt:

yum install epel-release -y
yum install certbot python3-certbot-apache -y

申请证书:

certbot --apache

2. 强制 HTTPS

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>

五、访问控制与防攻击

1. 防止 DoS(mod_evasive)

yum install mod_evasive -y

基本配置:

<IfModule mod_evasive20.c>
    DOSHashTableSize 3097
    DOSPageCount 10
    DOSSiteCount 50
    DOSBlockingPeriod 60
</IfModule>

2. 限制请求大小

防止大文件攻击:

LimitRequestBody 1048576

六、日志与监控

1. 日志审计

tail -f /var/log/httpd/access_log
tail -f /var/log/httpd/error_log

2. 防止日志被篡改

chmod 600 /var/log/httpd/*

七、推荐安全配置清单 ✅

项目 状态
隐藏版本信息
禁用目录浏览
开启 HTTPS
开启 SELinux
防火墙限制端口
限制敏感目录

八、一键检查建议

httpd -S
apachectl configtest

如果你愿意,我可以:

  • ✅ 帮你生成完整加固版 httpd.conf
  • ✅ 针对 Web 应用(PHP / Laravel / WordPress) 单独优化
  • ✅ 给你一份 CentOS + Apache 安全基线清单(可用于等保)

只要告诉我你的 CentOS 版本和用途即可。

0