Linux Apache2 网站加速实操指南
一 基础与连接优化
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
sudo a2enmod deflate
在配置中加入:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
AddOutputFilterByType DEFLATE image/svg+xml image/x-icon
AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject application/x-font-ttf font/opentype
</IfModule>
sudo a2enmod http2
在虚拟主机启用:Protocols h2 http/1.1
sudo a2dismod module_name
sudo a2enmod status
在配置中:ExtendedStatus On
<Location "/server-status">
SetHandler server-status
Require local
</Location>
以上措施能显著降低首字节时间(TTFB)并提升并发处理能力,建议优先实施。
二 缓存策略
sudo a2enmod expires
配置示例:<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "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/html "access plus 1 day"
</IfModule>
sudo a2enmod cache
sudo a2enmod cache_disk
配置示例(按站点或全局):<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheDirLevels 2
CacheDirLength 1
CacheIgnoreHeaders Set-Cookie
CacheIgnoreNoLastMod On
CacheDefaultExpire 3600
CacheMaxExpire 86400
</IfModule>
</IfModule>
curl -I https://your-domain/static/app.js
关注 Cache-Control、Expires、ETag 等字段是否生效。
通过“客户端强缓存 + 网关/代理缓存”的组合,可大幅减少源站计算与网络往返。三 并发与 MPM 调优
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
ServerLimit 256
MaxRequestWorkers 256
MaxConnectionsPerChild 4000
</IfModule>
四 全链路加速与系统层面优化
; php.ini
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.validate_timestamps=0 ; 生产环境建议关闭,配合部署刷新
五 验证与回滚
sudo apache2ctl configtest
sudo systemctl reload apache2 # 或 restart,视变更范围而定