在 CentOS 上保护 Apache(httpd)主要从系统层面、Apache 配置层面、网络层面和应用层面四个方向入手。下面给你一套实用且可落地的加固方案,适用于 CentOS 7 / 8 / Stream。
yum update -y
或(CentOS 8 / Stream):
dnf update -y
rm -f /var/www/html/index.html
CentOS 默认已使用 apache 用户,确认:
ps aux | grep httpd
编辑:
vim /etc/httpd/conf/httpd.conf
添加或修改:
ServerTokens Prod
ServerSignature Off
重启:
systemctl restart httpd
防止泄露目录结构:
<Directory /var/www/html>
Options -Indexes
</Directory>
只允许 GET / POST:
<Location />
AllowMethods GET POST
</Location>
<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>
.git / .env 等文件<FilesMatch "^\.(git|env|log|sql|conf)$">
Require all denied
</FilesMatch>
systemctl enable firewalld
systemctl start firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
只开放必要端口(80 / 443)
✅ 不要关闭 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
可使用 Let’s Encrypt:
yum install epel-release -y
yum install certbot python3-certbot-apache -y
申请证书:
certbot --apache
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
yum install mod_evasive -y
基本配置:
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 10
DOSSiteCount 50
DOSBlockingPeriod 60
</IfModule>
防止大文件攻击:
LimitRequestBody 1048576
tail -f /var/log/httpd/access_log
tail -f /var/log/httpd/error_log
chmod 600 /var/log/httpd/*
| 项目 | 状态 |
|---|---|
| 隐藏版本信息 | ✅ |
| 禁用目录浏览 | ✅ |
| 开启 HTTPS | ✅ |
| 开启 SELinux | ✅ |
| 防火墙限制端口 | ✅ |
| 限制敏感目录 | ✅ |
httpd -S
apachectl configtest
如果你愿意,我可以:
只要告诉我你的 CentOS 版本和用途即可。