Apache 性能优化 #

性能优化概述 #

优化方向 #

text
┌─────────────────────────────────────────────────────────────┐
│                    Apache 性能优化方向                       │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  配置优化                                                   │
│  ├── MPM 配置调优                                           │
│  ├── 连接参数优化                                           │
│  └── 模块精简                                               │
│                                                             │
│  内容优化                                                   │
│  ├── 压缩传输                                               │
│  ├── 缓存策略                                               │
│  └── 静态资源优化                                           │
│                                                             │
│  系统优化                                                   │
│  ├── 内核参数调优                                           │
│  ├── 文件描述符限制                                         │
│  └── 网络参数优化                                           │
│                                                             │
│  架构优化                                                   │
│  ├── 负载均衡                                               │
│  ├── CDN 加速                                               │
│  └── 反向代理                                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

MPM 配置优化 #

MPM 类型选择 #

text
┌─────────────────────────────────────────────────────────────┐
│                    MPM 类型对比                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Prefork MPM                                                │
│  ├── 多进程模型,每个请求一个进程                           │
│  ├── 稳定性高,进程隔离                                     │
│  ├── 内存占用大                                             │
│  └── 适合非线程安全模块(如 mod_php)                       │
│                                                             │
│  Worker MPM                                                 │
│  ├── 多进程 + 多线程模型                                     │
│  ├── 内存占用较小                                           │
│  ├── 并发能力强                                             │
│  └── 需要线程安全模块                                       │
│                                                             │
│  Event MPM(推荐)                                          │
│  ├── Worker 的改进版                                        │
│  ├── 事件驱动,异步处理                                     │
│  ├── 高并发性能最佳                                         │
│  └── Keep-Alive 优化                                        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

查看当前 MPM #

bash
# 查看当前使用的 MPM
apache2ctl -V | grep MPM    # Ubuntu/Debian
httpd -V | grep MPM         # CentOS/RHEL

# 查看可用 MPM
ls /etc/apache2/mods-available/mpm_*

# 切换 MPM(Ubuntu/Debian)
sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2

Prefork MPM 配置 #

apache
# ============================================
# Prefork MPM 配置
# ============================================

<IfModule mpm_prefork_module>
    # 初始启动的进程数
    StartServers             5
    
    # 最小空闲进程数
    MinSpareServers          5
    
    # 最大空闲进程数
    MaxSpareServers         10
    
    # 最大并发请求数
    MaxRequestWorkers      150
    
    # 每个进程最大请求数(0 表示无限制)
    MaxConnectionsPerChild   0
</IfModule>

# 根据服务器内存计算
# 假设每个进程占用 50MB 内存
# 8GB 内存服务器:MaxRequestWorkers = 8000 / 50 = 160
<IfModule mpm_prefork_module>
    StartServers            8
    MinSpareServers         8
    MaxSpareServers        16
    MaxRequestWorkers     150
    MaxConnectionsPerChild 1000
</IfModule>

Worker MPM 配置 #

apache
# ============================================
# Worker MPM 配置
# ============================================

<IfModule mpm_worker_module>
    # 初始启动的进程数
    StartServers             2
    
    # 最小空闲线程数
    MinSpareThreads         25
    
    # 最大空闲线程数
    MaxSpareThreads         75
    
    # 每个进程的最大线程数
    ThreadLimit             64
    
    # 每个进程创建的线程数
    ThreadsPerChild         25
    
    # 最大并发请求数
    MaxRequestWorkers      150
    
    # 每个进程最大请求数
    MaxConnectionsPerChild   0
</IfModule>

# 高并发配置
<IfModule mpm_worker_module>
    StartServers             4
    MinSpareThreads         50
    MaxSpareThreads        150
    ThreadLimit            128
    ThreadsPerChild         50
    MaxRequestWorkers     400
    MaxConnectionsPerChild 1000
</IfModule>

Event MPM 配置(推荐) #

apache
# ============================================
# Event MPM 配置(推荐)
# ============================================

<IfModule mpm_event_module>
    # 初始启动的进程数
    StartServers             2
    
    # 最小空闲线程数
    MinSpareThreads         25
    
    # 最大空闲线程数
    MaxSpareThreads         75
    
    # 线程限制
    ThreadLimit             64
    
    # 每个进程的线程数
    ThreadsPerChild         25
    
    # 最大并发请求数
    MaxRequestWorkers      150
    
    # 每个进程最大连接数
    MaxConnectionsPerChild   0
</IfModule>

# 高性能配置(8核 16GB 内存)
<IfModule mpm_event_module>
    ServerLimit             32
    StartServers             4
    MinSpareThreads        100
    MaxSpareThreads        200
    ThreadLimit            128
    ThreadsPerChild        100
    MaxRequestWorkers     3200
    MaxConnectionsPerChild 10000
</IfModule>

# 中等配置(4核 8GB 内存)
<IfModule mpm_event_module>
    ServerLimit             16
    StartServers             2
    MinSpareThreads         50
    MaxSpareThreads        100
    ThreadLimit             64
    ThreadsPerChild         50
    MaxRequestWorkers      800
    MaxConnectionsPerChild 5000
</IfModule>

MPM 参数计算 #

text
┌─────────────────────────────────────────────────────────────┐
│                    MPM 参数计算方法                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  MaxRequestWorkers 计算:                                   │
│                                                             │
│  公式:可用内存 / 每个进程/线程占用内存                     │
│                                                             │
│  示例:                                                     │
│  - 服务器内存:16GB                                         │
│  - 系统预留:4GB                                            │
│  - 可用内存:12GB                                           │
│  - 每个进程内存:50MB                                       │
│  - MaxRequestWorkers = 12000 / 50 = 240                    │
│                                                             │
│  ServerLimit 计算(Event/Worker):                         │
│                                                             │
│  ServerLimit = MaxRequestWorkers / ThreadsPerChild         │
│                                                             │
│  示例:                                                     │
│  - MaxRequestWorkers = 800                                  │
│  - ThreadsPerChild = 50                                     │
│  - ServerLimit = 800 / 50 = 16                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

连接优化 #

Keep-Alive 配置 #

apache
# ============================================
# Keep-Alive 连接优化
# ============================================

# 启用保持连接
KeepAlive On

# 每个连接最大请求数
MaxKeepAliveRequests 100

# 保持连接超时时间(秒)
KeepAliveTimeout 5

# Event MPM 专用配置
<IfModule mpm_event_module>
    # 启用 Keep-Alive
    KeepAlive On
    MaxKeepAliveRequests 100
    KeepAliveTimeout 5
</IfModule>

超时配置 #

apache
# ============================================
# 超时配置
# ============================================

# 请求超时(秒)
Timeout 60

# 连接超时
# 在虚拟主机中配置
<VirtualHost *:80>
    ServerName example.com
    
    # 连接超时
    Timeout 60
    
    # 请求体超时
    RequestReadTimeout header=20 body=60
</VirtualHost>

模块优化 #

禁用不必要的模块 #

bash
# Ubuntu/Debian 禁用模块
sudo a2dismod autoindex    # 目录列表
sudo a2dismod status       # 服务器状态(生产环境禁用)
sudo a2dismod info         # 服务器信息
sudo a2dismod userdir      # 用户目录
sudo a2dismod cgi          # CGI(如不需要)

# 重启 Apache
sudo systemctl restart apache2

查看已加载模块 #

bash
# 查看已加载模块
apache2ctl -M

# 查看模块数量
apache2ctl -M | wc -l

.htaccess 优化 #

禁用 .htaccess #

apache
# ============================================
# 禁用 .htaccess(提升性能)
# ============================================

<Directory /var/www/html>
    AllowOverride None
</Directory>

# 仅在需要的地方启用
<Directory /var/www/html/cms>
    AllowOverride All
</Directory>

合并 .htaccess 到主配置 #

apache
# ============================================
# 将 .htaccess 规则移到主配置文件
# ============================================

# 不推荐:分散在 .htaccess
# .htaccess 文件
RewriteEngine On
RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L]

# 推荐:集中到主配置
<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html
    
    <Directory /var/www/html>
        AllowOverride None
        
        RewriteEngine On
        RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L]
    </Directory>
</VirtualHost>

系统内核优化 #

文件描述符限制 #

bash
# ============================================
# 文件描述符限制
# ============================================

# 查看当前限制
ulimit -n

# 临时修改
ulimit -n 65535

# 永久修改
# /etc/security/limits.conf
*    soft    nofile    65535
*    hard    nofile    65535
root soft    nofile    65535
root hard    nofile    65535

# Apache 服务限制
# /etc/systemd/system/apache2.service.d/override.conf
[Service]
LimitNOFILE=65535

内核参数优化 #

bash
# ============================================
# 内核网络参数优化
# ============================================

# /etc/sysctl.conf

# TCP 优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 15

# 文件描述符
fs.file-max = 1000000

# 应用配置
sudo sysctl -p

监控与分析 #

服务器状态 #

apache
# ============================================
# 启用服务器状态监控
# ============================================

# 加载模块
LoadModule status_module modules/mod_status.so

# 配置访问
<Location /server-status>
    SetHandler server-status
    Require ip 192.168.1.0/24
</Location>

# 扩展状态信息
ExtendedStatus On

性能分析工具 #

bash
# ab - Apache Benchmark
ab -n 1000 -c 100 http://example.com/

# wrk
wrk -t 4 -c 100 -d 30s http://example.com/

# htop 查看资源
htop

# 查看连接数
ss -s
netstat -an | grep :80 | wc -l

完整优化配置 #

apache
# ============================================
# 完整性能优化配置
# ============================================

# MPM 配置
<IfModule mpm_event_module>
    ServerLimit             16
    StartServers             4
    MinSpareThreads        100
    MaxSpareThreads        200
    ThreadLimit            128
    ThreadsPerChild        100
    MaxRequestWorkers     1600
    MaxConnectionsPerChild 10000
</IfModule>

# 连接优化
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
Timeout 60

# 压缩
<IfModule mod_deflate.c>
    DeflateCompressionLevel 6
    AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>

# 缓存
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType image/* "access plus 1 year"
</IfModule>

# 禁用 .htaccess
<Directory /var/www/html>
    AllowOverride None
    Options -Indexes +FollowSymLinks
    Require all granted
</Directory>

# 隐藏服务器信息
ServerTokens Prod
ServerSignature Off

下一步 #

掌握了性能优化后,继续学习 安全加固,了解 Apache 的安全配置最佳实践!

最后更新:2026-03-29