Apache配置优化网站速度的可落地方案
一 核心网络与协议优化
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
# 可选:对体积很小的资源不压缩,减少CPU开销
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|gz|bz2|pdf)$ no-gzip dont-vary
</IfModule>
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
LoadModule http2_module modules/mod_http2.so
# 在443虚拟主机中确保 SSLEngine on 后启用 H2
LoadModule ssl_module modules/mod_ssl.so
Listen 443
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /path/to/cert.crt
SSLCertificateKeyFile /path/to/private.key
SSLCertificateChainFile /path/to/chain.pem
</VirtualHost>
二 缓存策略
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType text/html "access plus 1 hour"
</IfModule>
<IfModule mod_headers.c>
<Location "/static">
Header set Cache-Control "max-age=31536000, public"
</Location>
</IfModule>
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
CacheIgnoreHeaders Set-Cookie
</IfModule>
</IfModule>
LoadModule file_cache_module modules/mod_file_cache.so
CacheFile /var/www/html/index.html
三 MPM并发与进程模型调优
<IfModule prefork.c>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
<IfModule mpm_worker_module>
StartServers 5
MinSpareThreads 5
MaxSpareThreads 10
MaxRequestWorkers 250
MaxConnectionsPerChild 0
</IfModule>
四 日志、模块与系统层面优化
LogLevel warn
CustomLog logs/access_log common
# LoadModule autoindex_module modules/mod_autoindex.so
# LoadModule dir_module modules/mod_dir.so
ab -n 1000 -c 100 https://your-site.com/
五 快速检查清单与注意事项
apachectl -M | grep -E 'deflate|expires|headers|http2|ssl|cache|cache_disk',缺失则启用对应模块。apachectl configtest 校验,再 systemctl restart httpd(或 apache2)滚动重启。no-gzip dont-vary 排除。