📘 完整版教程 v2.0
从架构设计原理到生产环境最佳实践,涵盖安装、配置、安全、性能优化等全部核心知识。支持交互式手风琴阅读,快速检索所需内容。
1
Apache HTTP Server 总体架构设计
1.1 架构概述
Apache HTTP Server 采用模块化架构设计,核心分为三个主要层次:
- 核心层 (Core):处理基本的 HTTP 协议交互、请求解析和响应生成
- MPM层 (Multi-Processing Module):管理进程和线程模型,决定如何处理并发连接
- 模块层 (Modules):提供扩展功能,如认证、压缩、URL重写等
1.2 架构层次图
┌─────────────────────────────────────────────────────────────┐ │ Client Requests │ └─────────────────────────┬───────────────────────────────────┘ │ ┌─────────────────────────▼───────────────────────────────────┐ │ Connection Layer │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ Socket │ │ SSL │ │ Keep │ │ Timeout │ │ │ │ Accept │ │ TLS │ │ Alive │ │ Handler │ │ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ └─────────────────────────┬───────────────────────────────────┘ │ ┌─────────────────────────▼───────────────────────────────────┐ │ MPM Layer (多处理模块) │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ Prefork │ │ Worker │ │ Event │ │ │ │ (进程模型) │ │ (线程模型) │ │ (事件驱动) │ │ │ └──────────┘ └──────────┘ └──────────┘ │ └─────────────────────────┬───────────────────────────────────┘ │ ┌─────────────────────────▼───────────────────────────────────┐ │ Core Processing Layer │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ Request │ │ Config │ │ Content │ │Response │ │ │ │ Parser │ │ Handler │ │ Handler │ │ Builder │ │ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ └─────────────────────────┬───────────────────────────────────┘ │ ┌─────────────────────────▼───────────────────────────────────┐ │ Module Layer (模块层) │ │ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ │ │ │mod_ssl│ │mod_php│ │mod_wri│ │mod_aut│ │mod_pro│ │ │ │ │ │ │ │te │ │h │ │xy │ │ │ └───────┘ └───────┘ └───────┘ └───────┘ └───────┘ │ └─────────────────────────────────────────────────────────────┘
1.3 请求处理生命周期
每个 HTTP 请求在 Apache 中经过以下阶段:
- URI Translation — 将 URL 映射到文件系统路径 (mod_alias, mod_rewrite)
- Header Parsing — 解析请求头信息
- Access Control — 基于 IP/主机名的访问控制 (mod_access)
- Authentication — 身份验证 (mod_auth_basic, mod_auth_digest)
- Authorization — 权限授权检查
- Content Handling — 内容类型处理和生成响应
- Logging — 记录访问日志
- 每个请求分配独立的内存池,请求结束自动释放
- 避免内存泄漏和碎片化
- 支持分层池结构 (per-process → per-connection → per-request)
- 提供
apr_palloc(),apr_pcalloc(),apr_pstrdup()等函数 /etc/apache2/— 主配置目录/etc/apache2/apache2.conf— 主配置文件/etc/apache2/sites-available/— 可用站点配置/etc/apache2/sites-enabled/— 已启用站点配置/var/www/html/— 默认文档根目录/var/log/apache2/— 日志目录/etc/httpd/— 主配置目录/etc/httpd/conf/httpd.conf— 主配置文件/etc/httpd/conf.d/— 附加配置文件/var/www/html/— 默认文档根目录/var/log/httpd/— 日志目录- ✅ 使用官方源或源码安装最新稳定版
- ✅ 禁用不必要的模块减少攻击面
- ✅ 以非 root 用户运行 (User/Group 指令)
- ✅ 配置防火墙仅允许 80/443 端口
- ✅ 隐藏版本信息 (ServerTokens Prod)
- ✅ 配置日志轮转防止磁盘占满
- ✅ 启用 SSL/TLS 强制 HTTPS
- ✅ 配置 Fail2Ban 防止暴力攻击
- 全局环境配置 — 控制整个 Apache 服务器的行为
- 主服务器配置 — 定义默认站点的参数
- 虚拟主机配置 — 定义多个站点的独立参数
- 基于名称的虚拟主机 (Name-based):多个域名共享同一 IP,根据 Host 头区分
- 基于 IP 的虚拟主机 (IP-based):每个域名绑定不同 IP 地址
- 基于端口的虚拟主机 (Port-based):不同站点监听不同端口
- 目录权限不足 (Linux 文件权限)
- SELinux 阻止访问
- 缺少
Require all granted指令 - Options Indexes 被禁用但目录下没有 index 文件
- .htaccess 语法错误
- CGI/PHP 脚本执行错误
- 模块冲突或配置错误
- 文件权限问题
- 后端服务未启动
- 后端服务响应超时
- 防火墙阻止后端端口
- ProxyPass 配置地址错误
- Keepalived + VIP:主备切换,故障自动转移
- Nginx/HAProxy + Apache:前端负载均衡,后端 Apache 处理动态请求
- CDN:静态资源分发,减轻源站压力
- 健康检查:定期探测后端服务可用性
- 配置同步:使用 Ansible/Puppet 统一管理多台服务器配置
- ☐ 使用 Event MPM,参数经过计算
- ☐ ServerTokens Prod,ServerSignature Off
- ☐ 仅启用 TLS 1.2 + TLS 1.3
- ☐ 配置强密码套件
- ☐ HTTP 强制跳转 HTTPS
- ☐ 配置 HSTS (至少1年)
- ☐ 启用 Gzip 压缩
- ☐ 配置浏览器缓存
- ☐ 禁用目录列表 (Options -Indexes)
- ☐ 敏感文件禁止访问
- ☐ 配置安全响应头
- ☐ 启用请求超时保护
- ☐ 配置 Fail2Ban
- ☐ 日志轮转已配置
- ☐ ModSecurity WAF (如有条件)
- ☐ 配置已加入版本控制
- ☐ 监控告警已设置
- ☐ 定期备份策略已建立
- ☐ 配置语法测试通过
- ☐ 压力测试已执行
💡 架构特点
Apache 的模块化设计允许通过 LoadModule 指令动态加载/卸载功能模块,无需重新编译服务器。这种设计使 Apache 在保持核心精简的同时拥有极强的扩展性。
1.4 核心数据结构
Apache 使用以下关键数据结构管理请求和资源:
| 结构体 | 作用 | 生命周期 |
|---|---|---|
request_rec | 单个 HTTP 请求的完整信息 | 单次请求 |
conn_rec | 客户端连接信息 | 连接持续期间 |
server_rec | 虚拟主机配置信息 | 服务器运行期间 |
apr_pool_t | 内存池管理 | 根据分配策略 |
ap_conf_vector_t | 配置向量存储 | 配置生命周期 |
1.5 内存管理机制
Apache 使用 APR (Apache Portable Runtime) 提供的内存池 (Pool) 机制:
2
安装与部署指南
2.1 各平台安装方法
Ubuntu / Debian 安装
# 更新软件包列表
sudo apt update
# 安装 Apache2
sudo apt install apache2 -y
# 启动并设为开机自启
sudo systemctl enable apache2
sudo systemctl start apache2
# 查看状态
sudo systemctl status apache2
# 查看版本
apache2 -v
重要目录结构:
CentOS / RHEL / Fedora 安装
# CentOS/RHEL 8+ / Fedora
sudo dnf install httpd -y
# CentOS 7
sudo yum install httpd -y
# 启动服务
sudo systemctl enable httpd
sudo systemctl start httpd
# 防火墙放行
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
# SELinux 设置 (如需)
sudo setsebool -P httpd_can_network_connect 1
重要目录结构:
源码编译安装
# 安装编译依赖
sudo apt install build-essential libpcre3 libpcre3-dev libssl-dev zlib1g-dev
# 下载 APR 和 APR-Util
wget https://downloads.apache.org/apr/apr-1.7.4.tar.gz
wget https://downloads.apache.org/apr/apr-util-1.6.3.tar.gz
wget https://downloads.apache.org/httpd/httpd-2.4.58.tar.gz
# 解压
tar -xzf httpd-2.4.58.tar.gz
tar -xzf apr-1.7.4.tar.gz
tar -xzf apr-util-1.6.3.tar.gz
# 将 APR 移入 httpd 源码目录
mv apr-1.7.4 httpd-2.4.58/srclib/apr
mv apr-util-1.6.3 httpd-2.4.58/srclib/apr-util
# 编译安装
cd httpd-2.4.58
./configure \
--prefix=/usr/local/apache2 \
--enable-so \
--enable-ssl \
--enable-rewrite \
--enable-headers \
--enable-expires \
--enable-deflate \
--with-mpm=event \
--with-included-apr
make -j$(nproc)
sudo make install
# 创建 systemd 服务文件
sudo vim /etc/systemd/system/httpd.service
Systemd 服务文件示例:
[Unit]
Description=Apache HTTP Server
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/apache2/bin/apachectl start
ExecStop=/usr/local/apache2/bin/apachectl stop
ExecReload=/usr/local/apache2/bin/apachectl graceful
PIDFile=/usr/local/apache2/logs/httpd.pid
[Install]
WantedBy=multi-user.target
2.2 版本选择指南
| 版本 | 特点 | 推荐场景 |
|---|---|---|
| 2.4.x (最新) | 支持 Event MPM、细粒度授权、异步读写 | 所有新项目 (强烈推荐) |
| 2.2.x (EOL) | 传统模型,已停止维护 | 遗留系统兼容 |
⚠️ 注意
Apache 2.2 系列已于 2018 年停止支持,存在已知安全漏洞。新项目务必使用 2.4.x 版本。
2.3 生产环境部署清单
3
配置文件详解
3.1 主配置文件结构
Apache 主配置文件包含三个主要部分:
# ================================
# 全局环境配置
# ================================
ServerRoot "/etc/httpd"
Listen 80
Listen 443
# 加载模块
LoadModule mpm_event_module modules/mod_mpm_event.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule headers_module modules/mod_headers.so
LoadModule deflate_module modules/mod_deflate.so
# 运行用户
User apache
Group apache
# ================================
# 主服务器配置
# ================================
ServerAdmin admin@example.com
ServerName www.example.com:80
DocumentRoot "/var/www/html"
# 目录权限
<Directory />
AllowOverride none
Require all denied
</Directory>
<Directory /var/www/html>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 日志配置
ErrorLog "logs/error_log"
LogLevel warn
CustomLog "logs/access_log" combined
# ================================
# 虚拟主机配置
# ================================
<VirtualHost *:80>
ServerName www.example.com
Redirect permanent / https://www.example.com/
</VirtualHost>
3.2 核心配置指令详解
| 指令 | 说明 | 推荐值 |
|---|---|---|
ServerRoot | Apache 安装根目录 | /etc/httpd 或 /etc/apache2 |
Listen | 监听端口和IP地址 | 80, 443 |
ServerName | 服务器主机名 | www.example.com |
DocumentRoot | 文档根目录 | /var/www/html |
ServerTokens | 响应头中的服务器信息 | Prod (最小化) |
ServerSignature | 错误页面中的服务器签名 | Off |
Timeout | 请求超时时间(秒) | 60-300 |
KeepAlive | 持久连接 | On |
MaxKeepAliveRequests | 单个连接最大请求数 | 100-200 |
KeepAliveTimeout | 持久连接超时时间 | 5秒 |
3.3 Directory 指令与权限控制
# 基本目录访问控制
<Directory /var/www/html>
# 选项控制
Options -Indexes +FollowSymLinks -ExecCGI
# 允许 .htaccess 覆盖配置
AllowOverride All
# Apache 2.4 授权语法
Require all granted
# 或基于IP限制
# Require ip 192.168.1.0/24
# Require ip 10.0.0.0/8
# 或基于域名限制
# Require host example.com
</Directory>
# 文件级别控制
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh)$">
Require all denied
</FilesMatch>
# URL路径控制
<Location /server-status>
SetHandler server-status
Require ip 127.0.0.1
Require ip 192.168.1.0/24
</Location>
3.4 Options 指令详解
| 选项 | 说明 | 安全性 |
|---|---|---|
Indexes | 目录列表显示 | 危险 |
FollowSymLinks | 跟随符号链接 | 注意 |
ExecCGI | 允许执行 CGI 脚本 | 危险 |
Includes | 服务器端包含 (SSI) | 注意 |
MultiViews | 内容协商 | 安全 |
SymLinksIfOwnerMatch | 仅跟随同所有者符号链接 | 安全 |
🚨 安全警告
生产环境建议:Options -Indexes -ExecCGI -Includes,仅在必要时启用特定选项。避免使用 Options All。
4
MPM (多处理模块) 详解
4.1 三种 MPM 模型对比
| 特性 | Prefork | Worker | Event |
|---|---|---|---|
| 处理模型 | 多进程、单线程 | 多进程、多线程 | 多进程、多线程 + 事件驱动 |
| 内存占用 | 高 (每进程独立) | 中等 | 最低 |
| 并发能力 | 低 | 高 | 最高 |
| 线程安全 | 不需要 (每进程隔离) | 需要 | 需要 |
| Keep-Alive 处理 | 占用整个进程 | 占用一个线程 | 仅占用监听器线程 |
| 适用场景 | mod_php (非线程安全) | 高并发静态内容 | 现代Web应用 (推荐) |
4.2 Event MPM 配置 (推荐)
# /etc/httpd/conf.modules.d/00-mpm.conf
# 确保只启用一个 MPM
# LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
# LoadModule mpm_worker_module modules/mod_mpm_worker.so
LoadModule mpm_event_module modules/mod_mpm_event.so
# Event MPM 参数配置
<IfModule mpm_event_module>
# 启动时创建的子进程数
StartServers 3
# 最小空闲线程数
MinSpareThreads 75
# 最大空闲线程数
MaxSpareThreads 250
# 每个子进程包含的线程数
ThreadsPerChild 25
# 同一时间允许的最大连接数
MaxRequestWorkers 600
# 每个子进程处理的最大请求数后重启
MaxConnectionsPerChild 10000
# 异步关闭超时
AsyncRequestWorkerFactor 2
</IfModule>
4.3 Worker MPM 配置
<IfModule mpm_worker_module>
StartServers 4
MinSpareThreads 50
MaxSpareThreads 200
ThreadsPerChild 25
MaxRequestWorkers 500
MaxConnectionsPerChild 5000
</IfModule>
4.4 Prefork MPM 配置
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 256
MaxConnectionsPerChild 4000
</IfModule>
4.5 参数计算公式
📊 MaxRequestWorkers 计算
公式: MaxRequestWorkers = (服务器总内存 - 系统预留) / 每个 Apache 进程平均内存
示例: 8GB 服务器,系统预留 1GB,每进程占用约 30MB MaxRequestWorkers = (8192 - 1024) / 30 ≈ 238
4.6 MPM 监控
# 启用 mod_status 监控
LoadModule status_module modules/mod_status.so
<Location /server-status>
SetHandler server-status
Require ip 127.0.0.1
# 启用扩展状态信息
ExtendedStatus On
</Location>
# 查看实时状态
curl http://localhost/server-status?auto
# 命令行快速查看
apachectl status
apachectl fullstatus
5
虚拟主机 (Virtual Host) 配置
5.1 虚拟主机类型
5.2 基于名称的虚拟主机 (最常用)
# /etc/httpd/conf.d/vhosts.conf
# ===== 站点1: www.example.com =====
<VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
ServerAdmin webmaster@example.com
DocumentRoot /var/www/example.com/public
<Directory /var/www/example.com/public>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 独立日志
ErrorLog /var/log/httpd/example.com-error.log
CustomLog /var/log/httpd/example.com-access.log combined
# 环境变量
SetEnv APP_ENV production
</VirtualHost>
# ===== 站点2: blog.example.com =====
<VirtualHost *:80>
ServerName blog.example.com
DocumentRoot /var/www/blog/public
<Directory /var/www/blog/public>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/blog-error.log
CustomLog /var/log/httpd/blog-access.log combined
</VirtualHost>
# ===== 站点3: API接口 =====
<VirtualHost *:80>
ServerName api.example.com
DocumentRoot /var/www/api/public
# API 不需要 .htaccess
<Directory /var/www/api/public>
Options -Indexes
AllowOverride None
Require all granted
</Directory>
# 跨域配置
Header always set Access-Control-Allow-Origin "https://www.example.com"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type, Authorization"
</VirtualHost>
5.3 基于 IP 的虚拟主机
# 监听多个 IP
Listen 192.168.1.100:80
Listen 192.168.1.101:80
<VirtualHost 192.168.1.100:80>
ServerName site1.example.com
DocumentRoot /var/www/site1
</VirtualHost>
<VirtualHost 192.168.1.101:80>
ServerName site2.example.com
DocumentRoot /var/www/site2
</VirtualHost>
5.4 Debian/Ubuntu 虚拟主机管理
# 创建配置文件
sudo nano /etc/apache2/sites-available/example.com.conf
# 启用站点 (创建符号链接到 sites-enabled)
sudo a2ensite example.com.conf
# 禁用站点
sudo a2dissite example.com.conf
# 测试配置
sudo apache2ctl configtest
# 重载配置
sudo systemctl reload apache2
# 查看已启用站点
ls -la /etc/apache2/sites-enabled/
5.5 通配符虚拟主机
# 支持 *.dev.example.com 动态路由
<VirtualHost *:80>
ServerName dev.example.com
ServerAlias *.dev.example.com
# 动态文档根目录
VirtualDocumentRoot /var/www/dev/%1
<Directory /var/www/dev>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
💡 最佳实践
每个虚拟主机使用独立的用户和权限组运行,配合 suPHP 或 PHP-FPM 实现隔离。使用 mod_ruid2 或 mod_itk 可增强多租户安全性。
6
SSL/TLS 安全配置
6.1 SSL 证书获取与安装
使用 Let's Encrypt (免费证书)
# 安装 Certbot
sudo apt install certbot python3-certbot-apache -y
# CentOS:
# sudo dnf install certbot python3-certbot-apache
# 自动获取并配置证书
sudo certbot --apache -d example.com -d www.example.com
# 仅获取证书 (手动配置)
sudo certbot certonly --webroot -w /var/www/html -d example.com
# 测试自动续期
sudo certbot renew --dry-run
# 证书会自动续期 (每60天检查一次)
自签名证书 (开发环境)
# 生成私钥
openssl genrsa -out server.key 2048
# 生成 CSR
openssl req -new -key server.key -out server.csr
# 生成自签名证书 (365天有效)
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
# 生成包含完整链的证书
openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout /etc/ssl/private/apache-selfsigned.key \
-out /etc/ssl/certs/apache-selfsigned.crt \
-subj "/C=CN/ST=Beijing/L=Beijing/O=MyOrg/CN=example.com"
6.2 SSL 虚拟主机配置 (高安全评分)
<VirtualHost *:443>
ServerName www.example.com
DocumentRoot /var/www/example.com/public
# SSL 引擎
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
# 如使用自签证书:
# SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
# SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
# ===== 高安全 SSL 配置 =====
# 仅允许 TLS 1.2 和 TLS 1.3
SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
# 强密码套件
SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384
SSLHonorCipherOrder on
# 启用 OCSP Stapling
SSLUseStapling on
SSLStaplingResponderTimeout 5
SSLStaplingReturnResponderErrors off
SSLStaplingCache shmcb:/var/run/ocsp(128000)
# 会话缓存
SSLSessionTickets off
SSLSessionCache shmcb:/var/run/ssl_scache(512000)
SSLSessionCacheTimeout 600
# ===== 安全头部 =====
# HTTP Strict Transport Security (HSTS)
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
# 防止点击劫持
Header always set X-Frame-Options "SAMEORIGIN"
# 防止 MIME 嗅探
Header always set X-Content-Type-Options "nosniff"
# 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'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;"
# Permissions Policy
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"
<Directory /var/www/example.com/public>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog /var/log/httpd/example.com-ssl-error.log
CustomLog /var/log/httpd/example.com-ssl-access.log combined
</VirtualHost>
6.3 HTTP 强制跳转 HTTPS
<VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
# 方法1: 使用 Rewrite (灵活)
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 方法2: 使用 Redirect (简单)
# Redirect permanent / https://www.example.com/
</VirtualHost>
6.4 SSL 安全等级对比
| 配置级别 | SSLProtocol | 安全评分 |
|---|---|---|
| 高安全 (推荐) | TLSv1.2 + TLSv1.3 | A+ |
| 中等 | TLSv1 + TLSv1.1 + TLSv1.2 + TLSv1.3 | B |
| 低 (不推荐) | SSLv3 + TLSv1.0 | F |
⚠️ 重要
SSLv3, TLS 1.0, TLS 1.1 已不再安全,存在已知漏洞 (POODLE, BEAST 等)。现代浏览器已停止支持这些版本。请务必仅启用 TLS 1.2 和 TLS 1.3。
7
反向代理与负载均衡
7.1 基本反向代理配置
# 加载必要模块
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
LoadModule headers_module modules/mod_headers.so
<VirtualHost *:80>
ServerName app.example.com
# 反向代理到后端应用 (如 Node.js, Python, Java)
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
# WebSocket 支持
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*) ws://127.0.0.1:3000/$1 [P,L]
# 传递真实客户端信息
RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-Port "443"
# 超时配置
ProxyTimeout 300
</VirtualHost>
7.2 负载均衡配置
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
# 定义负载均衡组
<Proxy "balancer://mycluster">
# 后端服务器
BalancerMember http://192.168.1.10:8080 route=node1 loadfactor=5
BalancerMember http://192.168.1.11:8080 route=node2 loadfactor=5
BalancerMember http://192.168.1.12:8080 route=node3 loadfactor=3
# 备用节点 (热备)
BalancerMember http://192.168.1.13:8080 route=node4 status=+H
# 负载均衡算法
ProxySet lbmethod=byrequests
# 会话粘滞
ProxySet stickysession=JSESSIONID|jsessionid
ProxySet scolonpathdelim=On
# 健康检查
ProxySet lbmethod=bybusyness
# 故障转移配置
ProxySet failontimeout=On
ProxySet nofailover=Off
# 负载均衡器管理界面
BalancerInherit Off
</Proxy>
<VirtualHost *:80>
ServerName www.example.com
# 代理到负载均衡组
ProxyPass / balancer://mycluster/
ProxyPassReverse / balancer://mycluster/
# 负载均衡管理器 (仅限管理IP访问)
<Location "/balancer-manager">
SetHandler balancer-manager
Require ip 192.168.1.0/24
</Location>
</VirtualHost>
7.3 负载均衡算法
| 算法 | 模块 | 说明 |
|---|---|---|
byrequests | mod_lbmethod_byrequests | 基于请求计数轮询 (默认) |
bytraffic | mod_lbmethod_bytraffic | 基于流量字节数分配 |
bybusyness | mod_lbmethod_bybusyness | 基于当前繁忙程度 (最少连接) |
heartbeat | mod_lbmethod_heartbeat | 基于心跳检测的健康状态 |
7.4 PHP-FPM 代理配置
# 使用 mod_proxy_fcgi 连接 PHP-FPM
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
<VirtualHost *:80>
ServerName php.example.com
DocumentRoot /var/www/php-app
# 将 .php 请求转发给 PHP-FPM
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost/"
# 或使用 TCP:
# SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
<Directory /var/www/php-app>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
💡 性能建议
反向代理场景建议使用 Event MPM,其事件驱动模型更适合长连接和异步IO。配合 ProxyTimeout 和连接池可显著提升吞吐量。
8
安全加固配置
8.1 信息隐藏
# 隐藏版本号和操作系统信息
ServerTokens Prod
ServerSignature Off
# 禁止 TRACE 方法 (防止 XST 攻击)
TraceEnable Off
# 移除 ETag 中的 inode 信息
FileETag MTime Size
8.2 防止目录遍历和敏感文件访问
# 禁止访问隐藏文件
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
# 禁止访问敏感目录
<DirectoryMatch "^/.*/(vendor|node_modules|\.git|\.env|backup|temp)/">
Require all denied
</DirectoryMatch>
# 禁止访问配置文件
<FilesMatch "\.(ini|log|conf|bak|sql|env|git)$">
Require all denied
</FilesMatch>
8.3 请求限制 (防 DDoS 和暴力攻击)
# 加载限制模块
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule ratelimit_module modules/mod_ratelimit.so
# 请求超时配置 (防止 Slowloris 攻击)
<IfModule reqtimeout_module>
RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500
</IfModule>
# 请求体大小限制
LimitRequestBody 10485760 # 10MB
# 请求头大小限制
LimitRequestFields 50
LimitRequestFieldSize 8190
LimitRequestLine 8190
# 带宽限速
<Location /downloads>
SetOutputFilter RATE_LIMIT
SetEnv rate-limit 512 # 512 KB/s
</Location>
8.4 安全头部配置
LoadModule headers_module modules/mod_headers.so
# 全局安全头部
<IfModule headers_module>
# 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: https:; font-src 'self' https:; connect-src 'self';"
# 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
Header always set X-XSS-Protection "1; mode=block"
# Referrer-Policy
Header always set Referrer-Policy "strict-origin-when-cross-origin"
# Permissions-Policy
Header always set Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()"
# 移除不必要的头部
Header unset X-Powered-By
Header unset Server
</IfModule>
8.5 ModSecurity (WAF) 配置
# 安装 ModSecurity
sudo apt install libapache2-mod-security2 -y
# 启用模块
sudo a2enmod security2
# 配置 ModSecurity
# /etc/modsecurity/modsecurity.conf
SecRuleEngine On # 开启检测与拦截模式
SecRequestBodyAccess On
SecResponseBodyAccess On
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
# 使用 OWASP CRS (Core Rule Set) 规则集
IncludeOptional /usr/share/modsecurity-crs/*.conf
IncludeOptional /usr/share/modsecurity-crs/rules/*.conf
# 审计日志
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:5|4(?!04))"
SecAuditLogParts ABIJDEFHZ
SecAuditLogType Serial
SecAuditLog /var/log/apache2/modsec_audit.log
8.6 Fail2Ban 集成
# /etc/fail2ban/filter.d/apache-auth.conf
[Definition]
failregex = ^%(__prefix_line)s\[.*?\] \[.*?\] \[client <HOST>(:\d+)?\] AH\d+:.*$
ignoreregex =
# /etc/fail2ban/jail.local
[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/*error.log
maxretry = 5
bantime = 3600
[apache-badbots]
enabled = true
port = http,https
filter = apache-badbots
logpath = /var/log/apache2/*access.log
maxretry = 2
bantime = 86400
🚨 安全清单
生产环境必须执行:隐藏版本信息、禁用目录列表、启用 HTTPS、配置 WAF、使用 Fail2Ban、定期更新、最小化模块加载、独立用户运行、配置审计日志。
9
性能优化与调优
9.1 静态资源压缩 (Gzip/Brotli)
# 启用 mod_deflate
LoadModule deflate_module modules/mod_deflate.so
LoadModule filter_module modules/mod_filter.so
<IfModule deflate_module>
# 启用压缩
SetOutputFilter DEFLATE
# 压缩级别 (1-9, 建议4-6)
DeflateCompressionLevel 6
# 需要压缩的 MIME 类型
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE application/x-font-woff
AddOutputFilterByType DEFLATE application/font-woff2
# 排除已压缩内容
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|zip|gz|bz2)$ no-gzip
# 浏览器兼容性
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# 最小压缩大小
DeflateMinFileLength 1024
# 内存使用
DeflateMemLevel 9
DeflateWindowSize 15
DeflateBufferSize 8096
</IfModule>
9.2 浏览器缓存控制
# 启用 mod_expires
LoadModule expires_module modules/mod_expires.so
<IfModule expires_module>
ExpiresActive On
# 默认缓存时间
ExpiresDefault "access plus 1 month"
# HTML 文档 (短缓存)
ExpiresByType text/html "access plus 1 hour"
# CSS 和 JavaScript
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
# 图片
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
# 字体
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType application/x-font-woff "access plus 1 year"
# 视频音频
ExpiresByType video/mp4 "access plus 1 year"
ExpiresByType audio/mpeg "access plus 1 year"
</IfModule>
# Cache-Control 头部
<IfModule headers_module>
# 静态资源长缓存
<FilesMatch "\.(css|js|jpg|jpeg|png|gif|webp|svg|woff2?|ttf|eot)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
# HTML 不缓存或使用短期缓存
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "public, max-age=3600, must-revalidate"
</FilesMatch>
</IfModule>
9.3 HTTP/2 配置
# 启用 HTTP/2 (需要 SSL)
LoadModule http2_module modules/mod_http2.so
<VirtualHost *:443>
ServerName www.example.com
# 启用 HTTP/2 协议
Protocols h2 http/1.1
# HTTP/2 相关配置
H2Direct on
H2Push on
H2PushPriority application/json 32
# 服务器推送 (预加载关键资源)
H2PushResource /css/main.css
H2PushResource /js/app.js
# HTTP/2 优化参数
H2WindowSize 65535
H2MinWorkers 4
H2MaxWorkers 100
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
9.4 MPM 性能参数优化
# Event MPM 高并发配置
<IfModule mpm_event_module>
# 基础参数
StartServers 4
MinSpareThreads 100
MaxSpareThreads 400
ThreadsPerChild 50
MaxRequestWorkers 1500
MaxConnectionsPerChild 0 # 0 = 无限
# Event 特有参数
AsyncRequestWorkerFactor 2
# 线程池优化
ThreadLimit 64
ServerLimit 32
</IfModule>
9.5 性能基准测试工具
| 工具 | 用途 | 安装 |
|---|---|---|
| ab (Apache Bench) | 基础 HTTP 压测 | 随 Apache 安装 |
| wrk | 高性能 HTTP 压测 | 源码编译 |
| vegeta | 分布式压测 | Go 安装 |
| JMeter | 复杂场景压测 | Java 应用 |
| siege | Web 压力测试 | apt install siege |
# Apache Bench 使用示例
# 发送1000个请求,并发100个
ab -n 1000 -c 100 http://www.example.com/
# 测试 POST 请求
ab -n 100 -c 10 -p data.json -T 'application/json' http://api.example.com/
# 测试 HTTPS
ab -n 1000 -c 100 https://www.example.com/
# 带认证
ab -n 100 -c 10 -A user:pass http://www.example.com/admin/
💡 优化总结
关键性能优化措施:使用 Event MPM、启用 Gzip/Brotli 压缩、配置浏览器缓存、启用 HTTP/2、使用反向代理分离动静、合理设置 MPM 参数、使用 CDN、开启 OCSP Stapling、优化 KeepAlive。
10
常用模块详解
10.1 mod_rewrite — URL 重写
LoadModule rewrite_module modules/mod_rewrite.so
# 基本重写规则
RewriteEngine On
# 将 www 重定向到非 www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# 移除 .html 后缀
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [L]
# 友好 URL (前端路由)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html [L]
# 基于 User-Agent 重定向
RewriteCond %{HTTP_USER_AGENT} "iphone|android" [NC]
RewriteRule ^(.*)$ https://m.example.com/$1 [R=302,L]
# 防止图片盗链
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,L]
# 维护模式
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ /maintenance.html [R=302,L]
10.2 mod_alias — 别名和重定向
LoadModule alias_module modules/mod_alias.so
# 目录别名
Alias /icons/ "/usr/share/apache2/icons/"
# ScriptAlias (CGI 脚本目录)
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
# 重定向
Redirect permanent /old-page https://www.example.com/new-page
Redirect 302 /temp https://www.example.com/other
# 正则重定向
RedirectMatch ^/blog/post/(.*)$ https://blog.example.com/$1
10.3 mod_auth — 认证授权
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authz_user_module modules/mod_authz_user.so
# 创建密码文件
# htpasswd -c /etc/httpd/.htpasswd admin
# htpasswd /etc/httpd/.htpasswd user2
# 目录认证
<Directory /var/www/html/admin>
AuthType Basic
AuthName "Admin Area - Restricted"
AuthUserFile /etc/httpd/.htpasswd
Require valid-user
# 或只允许特定用户
# Require user admin editor
# 或允许特定组
# AuthGroupFile /etc/httpd/.htgroups
# Require group administrators
</Directory>
# Digest 认证 (更安全,密码不以明文传输)
<Directory /var/www/html/secure>
AuthType Digest
AuthName "Secure Area"
AuthDigestDomain /secure/
AuthUserFile /etc/httpd/.htdigest
Require valid-user
</Directory>
10.4 mod_autoindex — 目录列表美化
LoadModule autoindex_module modules/mod_autoindex.so
<Directory /var/www/html/files>
Options +Indexes
# 忽略特定文件
IndexIgnore *.bak *.tmp .git .svn __pycache__
# 排序方式
IndexOptions +FancyIndexing
IndexOptions +HTMLTable
IndexOptions +NameWidth=*
IndexOptions +DescriptionWidth=*
IndexOptions +IconsAreLinks
IndexOptions +SuppressHTMLPreamble
IndexOptions +XHTML
IndexOptions +IgnoreCase
# 自定义图标
AddIcon /icons/pdf.gif .pdf
AddIcon /icons/zip.gif .zip .gz .tar
AddIcon /icons/image.gif .jpg .jpeg .png .gif
# 自定义头部和底部
HeaderName HEADER.html
ReadmeName FOOTER.html
</Directory>
10.5 推荐模块清单
| 模块 | 功能 | 必要性 |
|---|---|---|
| mod_ssl | SSL/TLS 加密 | 必须 |
| mod_rewrite | URL 重写 | 必须 |
| mod_headers | HTTP 头部控制 | 必须 |
| mod_deflate | Gzip 压缩 | 必须 |
| mod_expires | 缓存控制 | 推荐 |
| mod_proxy | 反向代理 | 推荐 |
| mod_http2 | HTTP/2 支持 | 推荐 |
| mod_status | 服务器状态监控 | 可选 |
| mod_info | 服务器信息 | 开发环境 |
11
.htaccess 完全指南
11.1 什么是 .htaccess
.htaccess 是 Apache 的分布式配置文件,允许在每个目录级别覆盖全局配置。它使得非管理员用户也能配置自己目录的 Web 行为。
⚠️ 性能警告
Apache 每次处理请求时都会查找目录树中所有的 .htaccess 文件,这会带来性能开销。生产环境中如果可能,应将配置移入主配置文件并设置 AllowOverride None。
11.2 启用 .htaccess
# 主配置文件中允许 .htaccess 覆盖
<Directory /var/www/html>
# All = 允许所有覆盖
# None = 禁止所有覆盖
# AuthConfig = 仅允许认证相关指令
# FileInfo = 仅允许文件类型和重写
# Options = 仅允许 Options 指令
AllowOverride All
# 或精确指定
# AllowOverride FileInfo Options AuthConfig
Require all granted
</Directory>
11.3 万能 .htaccess 模板
# ============================================
# 完整 .htaccess 配置模板
# ============================================
# --- 重写引擎 ---
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# 强制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 强制 www (或去 www)
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
# 移除尾部斜杠
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
# 移除 .html 扩展名
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [L]
# 前端路由 (SPA 支持)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html [L]
</IfModule>
# --- 错误页面 ---
ErrorDocument 404 /404.html
ErrorDocument 403 /403.html
ErrorDocument 500 /500.html
# --- 缓存控制 ---
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>
# --- Gzip 压缩 ---
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>
# --- 安全头部 ---
<IfModule mod_headers.c>
Header set X-Frame-Options "SAMEORIGIN"
Header set X-Content-Type-Options "nosniff"
Header set X-XSS-Protection "1; mode=block"
Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>
# --- 禁止目录列表 ---
Options -Indexes
# --- 保护敏感文件 ---
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
<FilesMatch "\.(env|log|ini|conf|bak|sql)$">
Require all denied
</FilesMatch>
# --- PHP 配置 (如支持) ---
<IfModule mod_php.c>
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value memory_limit 256M
php_flag display_errors Off
</IfModule>
# --- 设置默认字符集 ---
AddDefaultCharset UTF-8
# --- 自定义 MIME 类型 ---
AddType application/x-httpd-php .php
AddType image/webp .webp
AddType font/woff2 .woff2
11.4 IP 黑白名单
# 黑名单 (禁止访问)
<RequireAll>
Require all granted
Require not ip 192.168.1.100
Require not ip 10.0.0.0/24
Require not host badsite.com
</RequireAll>
# 白名单 (仅允许)
<RequireAll>
Require ip 192.168.1.0/24
Require ip 10.0.0.0/8
</RequireAll>
# 禁止特定国家 (需 GeoIP 模块)
<IfModule mod_geoip.c>
GeoIPEnable On
<RequireAll>
Require all granted
Require not env blocked_country
</RequireAll>
</IfModule>
12
故障排查与调试
12.1 常用诊断命令
# 检查配置语法
apachectl configtest
# 或
httpd -t
apache2ctl -t
# 查看已加载模块
apachectl -M
httpd -M
# 查看编译参数
apachectl -V
httpd -V
# 查看虚拟主机配置
apachectl -S
httpd -S
# 查看完整配置 (含默认值)
httpd -S -L
# 语法检查并显示配置行号
httpd -t -D DUMP_RUN_CFG
httpd -t -D DUMP_VHOSTS
httpd -t -D DUMP_MODULES
# 启动调试模式
httpd -X # 单进程模式 (不后台运行)
# 查看日志实时输出
tail -f /var/log/httpd/error_log
tail -f /var/log/apache2/error.log
# 按时间筛选日志
grep "2026-07-10" /var/log/httpd/access_log | tail -100
12.2 常见错误及解决方案
403 Forbidden
原因分析:
解决方案:
# 检查文件权限
ls -la /var/www/html/
# 设置正确权限
chmod 755 /var/www/html/
chown -R apache:apache /var/www/html/
# 检查 SELinux
getenforce
restorecon -R /var/www/html/
chcon -R -t httpd_sys_content_t /var/www/html/
# 确保配置正确
<Directory /var/www/html>
Require all granted
Options -Indexes
</Directory>
500 Internal Server Error
原因分析:
解决方案:
# 首先查看错误日志
tail -50 /var/log/httpd/error_log
# 测试 .htaccess 语法
# 临时注释掉可疑指令,逐行排查
# 检查 CGI 脚本权限
chmod 755 /var/www/cgi-bin/script.cgi
chmod +x /var/www/cgi-bin/script.cgi
# 临时禁用 .htaccess
# AllowOverride None (在主配置中)
502 Bad Gateway (反向代理)
原因分析:
解决方案:
# 测试后端服务是否运行
curl -I http://127.0.0.1:3000/
netstat -tlnp | grep 3000
ss -tlnp | grep 3000
# 增加超时时间
ProxyTimeout 600
ProxyPass / http://127.0.0.1:3000/ connectiontimeout=30 timeout=300
# 检查防火墙
firewall-cmd --list-all
iptables -L -n | grep 3000
AH00558: Could not reliably determine FQDN
原因: Apache 无法确定服务器的完全限定域名
解决方案:
# 在主配置文件中添加
ServerName localhost
# 或使用实际域名
ServerName www.example.com
# 或修改 /etc/hosts
127.0.0.1 localhost www.example.com
12.3 日志配置与分析
# 自定义日志格式
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D" combined_ext
LogFormat "%h %l %u %t \"%r\" %>s %b" common
# 各字段说明:
# %h - 客户端IP
# %l - 远程登录名 (通常 -)
# %u - 远程用户 (认证后)
# %t - 时间
# %r - 请求行
# %>s - 状态码
# %b - 响应大小
# %D - 处理时间 (微秒)
# %T - 处理时间 (秒)
# 条件日志 (仅记录错误)
SetEnvIf Request_URI "^/api/" api_request
CustomLog /var/log/httpd/api-access.log combined_ext env=api_request
# 日志轮转配置
# /etc/logrotate.d/httpd
/var/log/httpd/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
/bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
endscript
}
12.4 调试模式启动
# 前台单进程模式 (用于调试)
httpd -X -e debug
# 增加日志级别
LogLevel debug # 可选: debug, info, notice, warn, error, crit, alert, emerg
# 使用 strace 跟踪系统调用
strace -f -p $(cat /var/run/httpd/httpd.pid)
# 使用 tcpdump 抓包分析
tcpdump -i any port 80 -A -s 0
# 使用 curl 调试
curl -v http://www.example.com/
curl -I http://www.example.com/
curl --trace-ascii /tmp/trace.txt http://www.example.com/
13
生产环境最佳实践
13.1 生产环境完整配置模板
# /etc/httpd/conf/httpd.conf
# ================================
# 生产环境 Apache 配置
# ================================
# === 全局配置 ===
ServerRoot "/etc/httpd"
PidFile run/httpd.pid
Timeout 60
KeepAlive On
MaxKeepAliveRequests 200
KeepAliveTimeout 5
# 安全信息隐藏
ServerTokens Prod
ServerSignature Off
TraceEnable Off
# 运行用户
User apache
Group apache
# === 模块加载 (最小化) ===
LoadModule mpm_event_module modules/mod_mpm_event.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule headers_module modules/mod_headers.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule filter_module modules/mod_filter.so
LoadModule expires_module modules/mod_expires.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule http2_module modules/mod_http2.so
LoadModule status_module modules/mod_status.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
# === 监听端口 ===
Listen 80
Listen 443
# === 全局目录配置 ===
<Directory />
AllowOverride None
Require all denied
</Directory>
# === 全局安全头部 ===
<IfModule headers_module>
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 always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
</IfModule>
# === Gzip 压缩 ===
<IfModule deflate_module>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json image/svg+xml
</IfModule>
# === 请求超时保护 ===
<IfModule reqtimeout_module>
RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500
</IfModule>
# === 日志 ===
ErrorLog "logs/error_log"
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D" combined
CustomLog "logs/access_log" combined
# === 状态监控 (限制IP) ===
<Location /server-status>
SetHandler server-status
Require ip 127.0.0.1
Require ip 192.168.0.0/16
</Location>
# === 包含虚拟主机 ===
IncludeOptional conf.d/*.conf
13.2 部署架构建议
┌──────────────┐ ┌──────────────────────────────────┐ │ │ │ Load Balancer │ │ Internet │────▶│ (Apache + mod_proxy_balancer) │ │ Traffic │ │ + SSL Termination │ │ │ │ + Static File Serving │ └──────────────┘ └──────────┬───────────────────────┘ │ ┌─────────────────┼─────────────────┐ │ │ │ ┌─────────▼─────────┐ ┌────▼────────┐ ┌─────▼────────┐ │ App Server 1 │ │ App Server 2│ │ App Server 3 │ │ (Apache+PHP-FPM) │ │ (Same) │ │ (Same) │ │ Port: 8080 │ │ Port: 8080 │ │ Port: 8080 │ └───────────────────┘ └─────────────┘ └──────────────┘ │ │ │ └─────────────────┼─────────────────┘ │ ┌───────────▼──────────┐ │ Database / Cache │ │ (MySQL/Redis) │ └──────────────────────┘
13.3 监控与告警
# 服务器状态页面配置
LoadModule status_module modules/mod_status.so
<Location /server-status>
SetHandler server-status
Require ip 10.0.0.0/8 # 仅内网
ExtendedStatus On
</Location>
# 监控脚本示例
#!/bin/bash
# check_apache.sh
STATUS=$(curl -s http://localhost/server-status?auto)
WORKERS=$(echo "$STATUS" | grep "BusyWorkers" | awk '{print $2}')
IDLE=$(echo "$STATUS" | grep "IdleWorkers" | awk '{print $2}')
TOTAL=$(echo "$STATUS" | grep "Total Accesses" | awk '{print $3}')
MAX_WORKERS=600
THRESHOLD=80 # 80%
if [ $WORKERS -gt $((MAX_WORKERS * THRESHOLD / 100)) ]; then
echo "ALERT: Apache worker usage at $((WORKERS * 100 / MAX_WORKERS))%"
# 发送告警通知
fi
13.4 高可用与容灾
13.5 定期维护清单
| 维护项 | 频率 | 操作 |
|---|---|---|
| 版本更新 | 每月 | 检查并应用安全补丁 |
| SSL 证书续期 | 60天 | Let's Encrypt 自动续期 |
| 日志清理 | 每日 | logrotate 自动轮转 |
| 配置备份 | 每次修改后 | Git 版本控制 |
| 性能审计 | 每季度 | 压测和调整参数 |
| 安全扫描 | 每月 | Nikto/OpenVAS 扫描 |
| 模块审查 | 每半年 | 移除不需要的模块 |
13.6 生产环境最终检查清单
✨ 核心原则
最小权限 + 最小暴露 + 纵深防御。 仅加载必要模块,仅开放必要端口,仅允许必要访问,配置多层安全防护,持续监控和维护。