Ubuntu 上优化 Apache 的实用步骤
一 基线检查与模块管理
apachectl -V,确认 MPM 模块(event/worker/prefork)与服务器信息。sudo a2dismod autoindex、sudo a2enmod rewrite ssl。Options -Indexes;隐藏版本信息 ServerTokens Prod、ServerSignature Off。a2enmod deflate expires cache cache_disk;按需启用 a2enmod headers。sudo apache2ctl configtest,再重启:sudo systemctl restart apache2。二 选择并调优 MPM(并发模型)
sudo a2dismod mpm_prefork && sudo a2enmod mpm_event && sudo systemctl restart apache2。<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
ab/jmeter 配合 top/htop/netstat 观察瓶颈并迭代参数。三 连接、超时与压缩缓存
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 2
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
CacheIgnoreHeaders Set-Cookie
这些设置可显著降低带宽、减少后端计算与磁盘 I/O。
四 动态内容优化与安全加固
curl -sL https://raw.githubusercontent.com/richardforth/apache2buddy/master/apache2buddy.pl | sudo perl。五 监控验证与持续迭代
top/htop 观察 CPU/内存 与 负载,netstat -anp | grep :80 或 ss -s 查看连接状态,tail -f /var/log/apache2/error.log 跟踪错误。ab(如 ab -n 10000 -c 200 http://yourdomain/)或 jmeter 进行基线压测,验证 吞吐、延迟、错误率 与资源占用,再微调 MPM/KeepAlive/缓存 等参数。apache2ctl configtest,再滚动重启;在业务低峰期执行,并做好配置与数据的备份。