Apache配置优化提升网站流量
一 核心原则与基线
apachectl configtest、systemctl reload apache2/httpd,压测示例:ab -n 10000 -c 200 -k http://yourdomain/。二 关键配置优化清单
KeepAlive On、MaxKeepAliveRequests 100、KeepAliveTimeout 2–5(繁忙站点取低值,减少长连接占用)。<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 1000
</IfModule>
text/html text/plain text/css application/javascript application/json image/svg+xml 等。ExpiresActive On,如 image/* access plus 1 month,text/css application/javascript access plus 1 week,text/html access plus 1 hour。CacheRoot /var/cache/apache2/mod_cache_disk,CacheEnable disk /,CacheDirLevels 2,CacheDirLength 1,必要时 CacheIgnoreHeaders Set-Cookie。Timeout 30(或更低),LogLevel warn;访问日志用 rotatelogs 或 logrotate 做按日分割,降低 I/O 抖动。ServerTokens Prod、ServerSignature Off;按需添加安全头:X-Content-Type-Options nosniff、X-Frame-Options SAMEORIGIN、X-XSS-Protection "1; mode=block"。Listen 443 http2、Protocols h2 http/1.1,可改善并发与首包体验(需 HTTPS)。三 按场景的参数建议
MaxRequestWorkers 与后端(如 PHP-FPM 的 pm.max_children)匹配;静态资源尽量由 CDN/反向代理承载,减少 Apache 与后端压力。opcache.enable=1、opcache.memory_consumption=128、opcache.max_accelerated_files=4000、opcache.revalidate_freq=60)。MaxRequestWorkers,充分利用 事件驱动;加大浏览器与磁盘缓存;考虑在更前层使用 Nginx/HAProxy/CDN 做静态资源服务与压缩/缓存。KeepAliveTimeout、适度降低 MaxKeepAliveRequests;启用 压缩/缓存;必要时引入负载均衡(如 HAProxy/Nginx)横向扩展;用 监控与自动扩缩容配合限流/熔断策略。四 验证与监控
apachectl configtest、systemctl reload apache2/httpd;开放 80/443 防火墙端口(如 firewall-cmd --permanent --add-service=http --add-service=https && firewall-cmd --reload)。apachectl -t -D DUMP_MODULES | egrep "deflate|expires|cache|http2|status";压缩:curl -I -H "Accept-Encoding: gzip" https://yourdomain/ | grep -i content-encoding;缓存:curl -I https://yourdomain/static/app.js | grep -i expires;状态页:启用 mod_status,访问 /server-status(建议仅内网或鉴权访问)。ab -n 50000 -c 500 -k https://yourdomain/(长时与峰值分开测);对比 P95/P99 延迟、吞吐(req/s)、错误率与CPU/内存/带宽;逐步调大 MaxRequestWorkers 直至稳定或资源用尽,再回退一档作为线上值。五 常见误区与修正