CentOS Apache 网站速度优化实操指南
一 基础网络与连接优化
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
LogLevel warn
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_max_tw_buckets = 5000
# 使配置生效
sysctl -p
以上设置能减少连接建立/销毁次数、优化端口与半连接队列,对高并发站点尤为有效。二 启用压缩与静态资源缓存
# 检查模块
apachectl -M | grep deflate
# 配置示例
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
# 可选:压缩级别 1-9,9 最高(CPU 更高)
DeflateCompressionLevel 6
# 已压缩资源无需再压
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|zip|gz|bz2|rar|pdf)$ no-gzip dont-vary
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 30 days"
ExpiresByType application/javascript "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 image/svg+xml "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>
<IfModule mod_headers.c>
Header set Cache-Control "public, max-age=31536000" env=!no-cache
</IfModule>
压缩与缓存是最“低成本、高收益”的优化项,建议优先启用与验证。三 调整 MPM 并发模型与关键参数
httpd -V | grep -i mpm(常见:prefork、worker、event)/etc/httpd/conf.modules.d/00-mpm.conf 中启用对应模块(如 LoadModule mpm_event_module modules/mod_mpm_event.so),注释其他 MPM;随后重启 httpd。<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
ServerLimit 256
MaxRequestWorkers 150 # 依据内存与单进程占用调整
MaxConnectionsPerChild 10000
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 0
</IfModule>
四 启用 HTTP/2 与反向代理缓存加速
# 确认模块
apachectl -M | grep http2
# 在 SSL VirtualHost 中启用
Protocols h2 http/1.1
HTTP/2 多路复用可显著改善多资源页面的加载速度。vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "8080";
}
sub vcl_recv {
if (req.method == "PURGE") {
return(purge);
}
return(hash);
}
sub vcl_backend_response {
set beresp.ttl = 120s;
unset beresp.http.Set-Cookie;
}
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
</IfModule>
</IfModule>
HTTP/2 与反向代理/页面缓存适合中高流量站点,能显著降低后端压力与首包时间。五 验证与持续监控
curl -I 查看响应头 Content-Encoding: gzip。ab -n 10000 -c 200 https://your-site/top, ss -s, tail -f /var/log/httpd/error_log