Apache配置优化以减少延迟的实用清单
一 核心原则与快速判断
二 关键配置示例
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
<IfModule mod_deflate.c>
DeflateCompressionLevel 6
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json application/xml application/xhtml+xml
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|pdf|zip|rar)$ no-gzip dont-vary
Header append Vary Accept-Encoding
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 hour"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(ico|jpe?g|png|webp|css|js)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
</IfModule>
# Debian/Ubuntu
a2enmod http2
# 在虚拟主机或端口监听处增加
Protocols h2 http/1.1
<IfModule mod_cache.c>
CacheEnable disk /
CacheRoot "/var/cache/apache"
CacheDefaultExpire 3600
</IfModule>
HostnameLookups Off
CustomLog "|/usr/bin/rotatelogs -l /var/log/apache2/access_%Y%m%d.log 86400" combined
ErrorLog "|/usr/bin/rotatelogs -l /var/log/apache2/error_%Y%m%d.log 86400"
以上配置需结合站点实际与模块可用性启用与调整。
三 MPM选择与调优要点
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 400
</IfModule>
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
</IfModule>
四 验证与上线步骤
httpd -t # 语法检查
apachectl -M | grep -E 'deflate|expires|headers|cache|http2|mpm_'
ab -n 10000 -c 100 https://yourdomain/watch -n 1 "pgrep httpd | wc -l"、netstat -ant | grep :80 | wc -l五 常见陷阱与修正