以下是Ubuntu上优化Apache性能的关键措施:
更新系统与软件包
确保系统和Apache等软件包为最新版本,获取性能优化和安全补丁。
sudo apt update && sudo apt upgrade
选择合适的MPM模块
sudo a2dismod mpm_prefork # 禁用prefork
sudo a2enmod mpm_event # 启用event(或mpm_worker)
sudo systemctl restart apache2
调整MPM参数
根据服务器资源修改/etc/apache2/mods-available/mpm_*.conf
,例如:
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
启用KeepAlive
减少TCP连接开销,设置合理的超时和最大请求数:
KeepAlive On
KeepAliveTimeout 5
MaxKeepAliveRequests 100
使用缓存模块
mod_deflate
压缩文本、CSS、JS等。sudo a2enmod deflate
配置压缩类型:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
mod_expires
设置缓存过期时间。<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
</IfModule>
限制并发连接
通过MaxRequestWorkers
和MaxConnectionsPerChild
防止服务器过载,例如:
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
禁用不必要的模块
移除未使用的模块(如mod_rewrite
仅在需要时启用),减少资源占用:
sudo a2dismod 模块名
配置负载均衡(高流量场景)
使用Nginx或HAProxy作为反向代理,分散Apache压力。
监控与调优
htop
、top
监控系统资源,或通过mod_status
查看Apache状态。注意:修改配置前建议备份文件,测试环境验证后再应用到生产环境。