Apache2 页面加载速度优化实操指南
一 核心优化清单
二 关键配置示例
启用压缩(mod_deflate)
sudo a2enmod deflate
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
# 可选:压缩级别 Apache ≥ 2.4.25
DeflateCompressionLevel 6
# 可选:对已是压缩格式的资源跳过压缩
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|gz|bz2)$ no-gzip dont-vary
</IfModule>
浏览器缓存(mod_expires)
sudo a2enmod expires
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresDefault "access plus 2 days"
</IfModule>
KeepAlive 复用
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
HTTP/2(需 Apache ≥ 2.4.5 且启用 TLS)
sudo a2enmod http2
Protocols h2 http/1.1
TLS 与 OCSP Stapling
SSLEngine on
SSLCertificateFile /path/to/fullchain.pem
SSLCertificateKeyFile /path/to/privkey.pem
# 生成 DH 参数(一次即可)
# openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
SSLOpenSSLConfCmd DHParameters "/etc/ssl/certs/dhparam.pem"
SSLUseStapling On
SSLStaplingCache "shmcb:/var/run/stapling-cache(150000)"
SSLSessionCache "shmcb:/var/run/ssl_scache(512000)"
SSLSessionCacheTimeout 300
服务器端缓存(mod_cache_disk,按需)
sudo a2enmod cache
sudo a2enmod cache_disk
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
CacheMaxExpire 86400
CacheIgnoreHeaders Set-Cookie
CacheIgnoreNoLastMod On
</IfModule>
</IfModule>
MPM 选择与调优(以 event 为例,路径因发行版而异)
sudo a2enmod mpm_event
sudo a2dismod mpm_prefork mpm_worker # 视当前启用情况调整
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
三 验证与上线步骤
sudo apache2ctl configtest
sudo systemctl reload apache2 # 或 restart
四 进阶与注意事项