以下是在CentOS上优化Apache2响应速度的关键方法:
启用KeepAlive
在/etc/httpd/conf/httpd.conf
中设置:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
减少连接建立开销,提升并发处理能力。
调整MPM模块参数
根据服务器负载选择prefork
/worker
/event
模块(CentOS 7默认prefork
),编辑/etc/httpd/conf.modules.d/00-mpm.conf
,例如:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
</IfModule>
优化并发连接数,避免资源浪费。
静态文件缓存
使用mod_expires
模块设置缓存时间:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType text/css "access plus 30 days"
</IfModule>
减少静态资源重复请求。
启用Gzip压缩
通过mod_deflate
压缩文本类资源:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
降低传输数据量,加快页面加载。
优化内核参数
编辑/etc/sysctl.conf
,调整TCP性能:
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_syn_backlog = 8192
net.core.somaxconn = 1024
提升网络连接效率。
禁用不必要的模块
注释httpd.conf
中未使用的模块(如mod_rewrite
等),减少内存占用。
硬件与系统优化
监控与调优
使用top
、htop
、ab
等工具监控性能,根据结果调整参数。
修改后需重启Apache服务:systemctl restart httpd
,确保配置生效。