在CentOS上优化Apache2以提供更好的静态资源服务,可以通过以下步骤进行:
启用并配置缓存模块:
mod_cache和mod_cache_disk模块,这些模块可以帮助Apache缓存静态内容。sudo a2enmod cache
sudo a2enmod cache_disk
/etc/httpd/conf/httpd.conf或/etc/apache2/apache2.conf),添加或修改以下配置:<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
压缩静态资源:
mod_deflate模块来压缩文本文件(如HTML、CSS、JavaScript)。sudo a2enmod deflate
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
启用Gzip压缩:
mod_gzip模块已启用(如果可用)。sudo a2enmod gzip
<IfModule mod_gzip.c>
AddOutputFilterByType GZIP text/html text/plain text/xml text/css application/javascript
</IfModule>
优化KeepAlive设置:
KeepAlive以减少TCP连接的建立和关闭次数。sudo a2enmod keepalive
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
调整MaxClients和StartServers:
MaxClients和StartServers参数以优化并发连接处理。<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestsPerChild 0
</IfModule>
使用CDN:
日志优化:
LogLevel warn
CustomLog /var/log/httpd/access_log combined buffer=16k
ErrorLog /var/log/httpd/error_log
定期清理缓存:
sudo rm -rf /var/cache/apache2/mod_cache_disk/*
通过以上步骤,可以显著提高Apache2在CentOS上提供静态资源的性能。记得在每次修改配置后重启Apache服务以应用更改:
sudo systemctl restart httpd
或
sudo systemctl restart apache2