Apache 安全加固 #
安全概述 #
安全加固方向 #
text
┌─────────────────────────────────────────────────────────────┐
│ Apache 安全加固 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 信息隐藏 │
│ ├── 隐藏服务器版本 │
│ ├── 隐藏 PHP 版本 │
│ └── 自定义错误页面 │
│ │
│ 访问控制 │
│ ├── 目录访问限制 │
│ ├── 文件访问限制 │
│ └── IP 访问控制 │
│ │
│ 攻击防护 │
│ ├── DDoS 防护 │
│ ├── SQL 注入防护 │
│ ├── XSS 防护 │
│ └── 点击劫持防护 │
│ │
│ 传输安全 │
│ ├── SSL/TLS 配置 │
│ ├── 安全头配置 │
│ └── Cookie 安全 │
│ │
└─────────────────────────────────────────────────────────────┘
隐藏服务器信息 #
隐藏版本信息 #
apache
# ============================================
# 隐藏服务器版本信息
# ============================================
# 响应头中的服务器信息
ServerTokens Prod
# Prod: 仅显示 Apache
# Major: Apache/2
# Minor: Apache/2.4
# Min: Apache/2.4.52
# OS: Apache/2.4.52 (Unix)
# Full: Apache/2.4.52 (Unix) OpenSSL/1.1.1
# 错误页面底部签名
ServerSignature Off
# Off: 不显示
# On: 显示服务器信息
# EMail: 显示管理员邮箱
自定义错误页面 #
apache
# ============================================
# 自定义错误页面
# ============================================
# 全局错误页面
ErrorDocument 400 /error/400.html
ErrorDocument 401 /error/401.html
ErrorDocument 403 /error/403.html
ErrorDocument 404 /error/404.html
ErrorDocument 500 /error/500.html
ErrorDocument 502 /error/502.html
ErrorDocument 503 /error/503.html
# 在虚拟主机中配置
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
</VirtualHost>
目录和文件安全 #
禁止目录列表 #
apache
# ============================================
# 禁止目录列表
# ============================================
# 全局禁用
<Directory />
Options -Indexes
</Directory>
# 特定目录
<Directory /var/www/html>
Options -Indexes +FollowSymLinks
</Directory>
保护敏感文件 #
apache
# ============================================
# 保护敏感文件
# ============================================
# 禁止访问隐藏文件
<FilesMatch "^\.">
Require all denied
</FilesMatch>
# 禁止访问 .htaccess 和 .htpasswd
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
# 禁止访问备份文件
<FilesMatch "~$">
Require all denied
</FilesMatch>
# 禁止访问配置文件
<FilesMatch "\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist|env)$">
Require all denied
</FilesMatch>
# 禁止访问版本控制目录
RedirectMatch 404 /\.git
RedirectMatch 404 /\.svn
RedirectMatch 404 /\.hg
RedirectMatch 404 /\.env
# 禁止访问敏感目录
<DirectoryMatch "^\.|\.git|\.svn|\.env">
Require all denied
</DirectoryMatch>
限制目录访问 #
apache
# ============================================
# 限制目录访问
# ============================================
# 禁止访问根目录
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
# 仅允许 Web 根目录
<Directory /var/www/html>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 保护上传目录
<Directory /var/www/html/uploads>
Options -Indexes -FollowSymLinks -ExecCGI
# 禁止执行脚本
<FilesMatch "\.(php|phtml|php3|php4|php5|php7|phps)$">
Require all denied
</FilesMatch>
# 限制文件类型
<FilesMatch "\.(jpg|jpeg|png|gif|pdf|doc|docx)$">
Require all granted
</FilesMatch>
</Directory>
安全响应头 #
完整安全头配置 #
apache
# ============================================
# 安全响应头配置
# ============================================
<IfModule mod_headers.c>
# X-Frame-Options - 防止点击劫持
Header always set X-Frame-Options "SAMEORIGIN"
# X-Content-Type-Options - 防止 MIME 嗅探
Header always set X-Content-Type-Options "nosniff"
# X-XSS-Protection - XSS 保护
Header always set X-XSS-Protection "1; mode=block"
# Referrer-Policy - 引用策略
Header always set Referrer-Policy "strict-origin-when-cross-origin"
# Content-Security-Policy - 内容安全策略
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'self';"
# Permissions-Policy - 权限策略
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=()"
# Strict-Transport-Security - HSTS
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# X-Permitted-Cross-Domain-Policies
Header always set X-Permitted-Cross-Domain-Policies "none"
# 移除敏感头
Header unset X-Powered-By
Header unset Server
</IfModule>
安全头说明 #
text
┌─────────────────────────────────────────────────────────────┐
│ 安全响应头说明 │
├─────────────────────────────────────────────────────────────┤
│ │
│ X-Frame-Options │
│ 防止页面被嵌入到 iframe 中 │
│ DENY: 完全禁止 │
│ SAMEORIGIN: 仅同源允许 │
│ ALLOW-FROM: 指定来源 │
│ │
│ X-Content-Type-Options │
│ 防止浏览器 MIME 类型嗅探 │
│ nosniff: 禁用嗅探 │
│ │
│ X-XSS-Protection │
│ 启用浏览器 XSS 过滤器 │
│ 0: 禁用 │
│ 1: 启用 │
│ 1; mode=block: 启用并阻止 │
│ │
│ Content-Security-Policy │
│ 控制资源加载来源 │
│ default-src: 默认策略 │
│ script-src: 脚本来源 │
│ style-src: 样式来源 │
│ │
│ Strict-Transport-Security │
│ 强制使用 HTTPS │
│ max-age: 有效期(秒) │
│ includeSubDomains: 包含子域名 │
│ │
└─────────────────────────────────────────────────────────────┘
请求限制 #
限制请求大小 #
apache
# ============================================
# 限制请求大小
# ============================================
# 限制请求体大小(字节)
LimitRequestBody 10485760 # 10MB
# 限制请求头数量
LimitRequestFields 50
# 限制请求头大小
LimitRequestFieldSize 8190
# 限制请求行大小
LimitRequestLine 8190
# 在虚拟主机中配置
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
<Directory /var/www/html/uploads>
LimitRequestBody 52428800 # 50MB
</Directory>
</VirtualHost>
限制请求方法 #
apache
# ============================================
# 限制 HTTP 方法
# ============================================
# 仅允许 GET、POST、HEAD
<Directory /var/www/html>
<LimitExcept GET POST HEAD>
Require all denied
</LimitExcept>
</Directory>
# 禁止危险方法
<Directory /var/www/html>
<Limit DELETE PUT TRACE CONNECT>
Require all denied
</Limit>
</Directory>
# TRACE 方法禁用
TraceEnable Off
DDoS 防护 #
限速配置 #
apache
# ============================================
# 请求限速配置
# ============================================
# 加载模块
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule ratelimit_module modules/mod_ratelimit.so
# 请求超时配置
RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500
# 限制下载速度
<Location /downloads>
SetOutputFilter RATE_LIMIT
LimitRate 102400 # 100KB/s
</Location>
# 使用 mod_evasive(需安装)
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10
</IfModule>
连接限制 #
apache
# ============================================
# 连接限制
# ============================================
# 限制并发连接
# 使用 mod_limitipconn(需安装)
<IfModule mod_limitipconn.c>
<Location />
MaxConnPerIP 10
</Location>
<Location /downloads>
MaxConnPerIP 2
</Location>
</IfModule>
# 使用 mod_qos(需安装)
<IfModule mod_qos.c>
QS_SrvMaxConn 1000
QS_SrvMaxConnClose 500
QS_SrvMaxConnPerIP 20
</IfModule>
SSL 安全配置 #
SSL 协议配置 #
apache
# ============================================
# SSL 安全配置
# ============================================
# 仅允许 TLS 1.2 和 1.3
SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
# 或明确指定
SSLProtocol -all +TLSv1.2 +TLSv1.3
# 加密套件
SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384
# 优先使用服务器顺序
SSLHonorCipherOrder on
# HSTS
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# OCSP Stapling
SSLUseStapling on
SSLStaplingCache shmcb:/var/run/ocsp(128000)
日志安全 #
日志配置 #
apache
# ============================================
# 安全日志配置
# ============================================
# 详细日志级别
LogLevel warn
# 记录敏感信息
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-For}i\"" security
CustomLog ${APACHE_LOG_DIR}/access.log security
# 错误日志
ErrorLog ${APACHE_LOG_DIR}/error.log
日志监控 #
bash
# 监控异常请求
tail -f /var/log/apache2/access.log | grep -E " 4[0-9]{2} | 5[0-9]{2} "
# 监控 SQL 注入尝试
grep -i "union.*select\|select.*from" /var/log/apache2/access.log
# 监控 XSS 尝试
grep -i "<script\|javascript:" /var/log/apache2/access.log
# 监控路径遍历
grep -i "\.\./\.\." /var/log/apache2/access.log
完整安全配置 #
apache
# ============================================
# 完整安全配置示例
# ============================================
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
# 隐藏服务器信息
ServerTokens Prod
ServerSignature Off
# 安全响应头
<IfModule mod_headers.c>
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-Content-Type-Options "nosniff"
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header unset X-Powered-By
</IfModule>
# 目录安全
<Directory /var/www/html>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
<LimitExcept GET POST HEAD>
Require all denied
</LimitExcept>
</Directory>
# 保护敏感文件
<FilesMatch "^\.|~$|\.(bak|config|sql|log|env)$">
Require all denied
</FilesMatch>
# 禁止版本控制目录
RedirectMatch 404 /\.(git|svn|hg|env)
# 请求限制
LimitRequestBody 10485760
LimitRequestFields 50
# 自定义错误页面
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
# 日志
ErrorLog ${APACHE_LOG_DIR}/example-error.log
CustomLog ${APACHE_LOG_DIR}/example-access.log combined
</VirtualHost>
安全检查清单 #
text
┌─────────────────────────────────────────────────────────────┐
│ Apache 安全检查清单 │
├─────────────────────────────────────────────────────────────┤
│ │
│ □ 隐藏服务器版本信息 │
│ □ 禁用目录列表 │
│ □ 保护敏感文件(.htaccess, .env, .git) │
│ □ 配置安全响应头 │
│ □ 启用 HTTPS │
│ □ 配置 SSL 安全参数 │
│ □ 限制请求大小 │
│ □ 限制 HTTP 方法 │
│ □ 配置访问控制 │
│ □ 禁用不必要的模块 │
│ □ 配置错误页面 │
│ □ 定期更新 Apache 版本 │
│ □ 监控日志异常 │
│ │
└─────────────────────────────────────────────────────────────┘
下一步 #
掌握了安全加固后,继续学习 负载均衡,了解如何配置 Apache 负载均衡!
最后更新:2026-03-29