在CentOS上优化Apache2服务器的性能涉及多个方面,包括配置调整、启用缓存和压缩、使用多线程等。以下是一些具体的优化步骤和建议:
启用KeepAlive:在httpd.conf
中添加以下行来启用KeepAlive:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
这将设置最大KeepAlive请求数为100,并将超时时间设置为5秒。
调整MPM(多处理模块)设置:根据服务器硬件资源和负载情况,调整MPM设置可以提高并发处理能力。对于CentOS 7的Apache,使用的默认MPM是prefork
。你可以编辑Apache配置文件中的MPM配置:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
ServerLimit 256
MaxClients 256
MaxRequestsPerChild 2000
</IfModule>
配置静态文件缓存:使用mod_expires
模块来实现静态文件缓存。在Apache配置文件中添加以下行:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 30 days"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType application/javascript "access plus 30 days"
</IfModule>
启用压缩:启用Gzip压缩可以减小传输的数据量,提高网站加载速度。在Apache配置文件中添加以下行来启用Gzip压缩:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
mod_proxy
和mod_cache
模块来实现缓存代理。<IfModule mod_proxy.c>
ProxyRequests Off
ProxyPass / http://backend_server/
ProxyPassReverse / http://backend_server/
</IfModule>
<IfModule mod_cache.c>
CacheEnable disk /
CacheRoot /var/cache/apache2
CacheDirLevels 2
CacheDirLength 1
</IfModule>
mod_mpm_worker
或mod_mpm_event
模块来实现多线程支持。<IfModule mpm_worker_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
</IfModule>
mod_ssl
模块来实现SSL加速。<IfModule mod_ssl.c>
SSLEngine on
SSLCertificateFile /etc/ssl/certs/your_domain.crt
SSLCertificateKeyFile /etc/ssl/private/your_domain.key
</IfModule>
echo "1" > /proc/sys/net/ipv4/tcp_syncookies
执行以下命令使内核配置立马生效:/sbin/sysctl -p
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
通过以上优化策略,可以显著提高CentOS上Apache2服务器的性能和响应速度。根据具体需求和环境,可能还有其他优化策略适用。记得在每次更改配置文件之后重新启动Apache服务以使更改生效。