Debian 上 Apache2 性能优化实用指南
一 基础准备与模块启用
sudo apt update && sudo apt upgrade。sudo a2enmod deflate expires headers http2 ssl rewrite(按需启用)。apache2ctl -M | grep -v \[a2_\] 查看已启用模块,使用 sudo a2dismod 模块名 禁用无用模块。sudo apache2ctl -V | grep MPM 查看当前 MPM,高并发优先使用 event(或 worker)。二 传输层与内容交付优化
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css \
application/javascript application/json application/x-javascript
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 hour"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
</IfModule>
sudo a2enmod http2,在虚拟主机启用 Protocols h2 http/1.1。<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot /var/cache/apache2/mod_cache_disk
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
ServerSignature Off、ServerTokens Prod。三 MPM 并发与 KeepAlive 调优
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
Timeout 30
# mpm_event.conf
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
估算思路:若单进程/线程常驻内存约为 M MB,则并发上限近似为 MaxRequestWorkers ≤ 可用内存 / M;先保守设置,再结合监控逐步上调。MaxRequestWorkers(旧称 MaxClients)与 MaxConnectionsPerChild,避免内存膨胀。四 启用 HTTPS 与 TLS 优化
sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048。SSLOpenSSLConfCmd DHParameters "/etc/ssl/certs/dhparam.pem"
SSLUseStapling On
SSLStaplingCache "shmcb:/var/run/stapling-cache(150000)"
SSLSessionCache "shmcb:/var/run/ssl_scache(512000)"
SSLSessionCacheTimeout 300
sudo apt install certbot python3-certbot-apache,然后 sudo certbot --apache -d yourdomain.com。SSLCompression off,并优先使用 ECDHE 套件与 TLSv1.2/1.3。五 监控 日志 与系统层优化
sudo a2enmod status 并在虚拟主机配置 ExtendedStatus On,访问 /server-status 查看并发、请求耗时等。htop、apachetop、netstat -tnp | grep :80,定位瓶颈与异常连接。LogLevel warn;按需分离与轮转访问/错误日志,避免磁盘 I/O 成为瓶颈。sudo sysctl -w net.core.somaxconn=4096、net.ipv4.tcp_tw_reuse=1。net.core.rmem_max、net.core.wmem_max。ab/wrk 或真实流量压测,观察 CPU、内存、连接数、P95/P99 延迟,再迭代优化。