Apache配置优化提升CentOS网站用户体验
一 核心优化方向与预期收益
二 关键配置与示例
启用压缩与缓存(减少传输、降低重复请求)
# /etc/httpd/conf.d/performance.conf
LoadModule deflate_module modules/mod_deflate.so
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
LoadModule expires_module modules/mod_expires.so
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresDefault "access plus 2 days"
</IfModule>
说明:压缩让文本类资源体积显著下降;缓存让浏览器对图片、CSS、JS等“强缓存”,二次访问几乎秒开。
长连接与MPM调优(提升并发、降低握手开销)
# 启用持久连接(KeepAlive)
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
# 选择并调优 MPM(示例为 event,需与模块加载一致)
# 确认加载:httpd -V | grep -i mpm
# 在 /etc/httpd/conf.modules.d/00-mpm.conf 确保仅启用 mpm_event_module
LoadModule mpm_event_module modules/mod_mpm_event.so
# LoadModule mpm_prefork_module modules/mod_mpm_prefork.so # 注释
# LoadModule mpm_worker_module modules/mod_mpm_worker.so # 注释
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 1000
ServerLimit 16
</IfModule>
说明:KeepAlive复用TCP连接,适合多资源页面;event MPM在高并发与长连接场景更高效,配合线程与进程上限可显著减少排队与超时。
全站HTTPS与版本信息隐藏(安全与信任)
# 使用 certbot 获取并自动续期 Let’s Encrypt 证书
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
# 隐藏版本信息(减少攻击面与信息泄露)
ServerTokens Prod
ServerSignature Off
说明:HTTPS避免明文传输与劫持,提升搜索排名与用户信任;隐藏版本降低针对性攻击面。
精简模块与日志优化(降低开销、便于排障)
# 禁用不必要的模块(示例)
# LoadModule info_module modules/mod_info.so
# LoadModule status_module modules/mod_status.so
# LoadModule autoindex_module modules/mod_autoindex.so
# 日志轮转(避免单文件过大影响性能)
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_log.%Y-%m-%d 86400" combined
ErrorLog "|/usr/sbin/rotatelogs /var/log/httpd/error_log.%Y-%m-%d 86400"
# 动态内容加速(PHP)
# 在 /etc/php.ini 或相应 pool 配置中启用 OPcache
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
说明:精简模块减少内存与攻击面;按天轮转日志避免磁盘与I/O抖动;OPcache显著降低PHP执行时间波动。
三 验证与上线流程
sudo httpd -t # 语法检查
sudo systemctl reload httpd # 平滑生效
sudo systemctl restart httpd # 必要时重启
curl -I https://yourdomain.com
sudo firewall-cmd --list-services | grep -E 'http|https'
# 实时状态页(ExtendedStatus On 后可用)
lynx http://localhost/server-status
# 连接与负载
ss -s
top
# 基准测试(小流量先试)
ab -n 1000 -c 50 https://yourdomain.com/
建议:先在测试环境验证,再灰度上线;持续观察首包时间、TTFB、成功率与错误率,结合监控与日志滚动分析。四 场景化建议