Apache静态资源优化实操指南
一 启用压缩与连接复用
sudo a2enmod deflate;在 CentOS/RHEL 确认已安装 mod_deflate。<IfModule mod_deflate.c>
# 压缩文本与脚本类资源
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css \
application/javascript application/x-javascript application/xml \
application/xhtml+xml image/svg+xml
# 避免对已经压缩的二进制图片重复压缩
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
# 兼容老浏览器
BrowserMatch ^Mozilla/4 gzip-only-text/html
# 让缓存按 Accept-Encoding 区分版本
Header append Vary Accept-Encoding
# 压缩级别:1-9,默认通常为 6,兼顾压缩率与 CPU
DeflateCompressionLevel 6
</IfModule>
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
curl -I 中查看响应头是否出现 Content-Encoding: gzip。二 设置强缓存与验证
sudo a2enmod expires headers;在 CentOS/RHEL 确认已加载 mod_expires 与 mod_headers。# 1) 使用 Expires 模块设置 Expires 与 Cache-Control
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 year"
</IfModule>
# 2) 用 Headers 精细控制
<IfModule mod_headers.c>
# 对带指纹/版本号的资源设置“强缓存”
<FilesMatch "\.(css|js|png|jpe?g|gif|svg|woff2?|ico)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
# 对可能频繁变动的资源设置“协商缓存”
<FilesMatch "\.(html|json)$">
Header set Cache-Control "public, max-age=0, must-revalidate"
</FilesMatch>
</IfModule>
access plus 1 month、now plus 30 days、A2592000(从访问时计算)modification plus 5 hours 3 minutes、M604800(从文件最后修改时间计算,M 仅对静态文件有效)三 启用 HTTP/2 与资源分发
sudo a2enmod http2(Debian/Ubuntu);编译时加入 --enable-http2(源码)。<IfModule mod_http2.c>
Protocols h2 http/1.1
</IfModule>
四 资源本身与运维优化
app.a1b2c3.js)解决强缓存更新问题。a2dismod <module>),降低内存占用与攻击面。五 一键检查与常见问题
apache2ctl -M | egrep 'deflate_module|expires_module|headers_module|http2_module'httpd -M | egrep 'deflate_module|expires_module|headers_module|http2_module'sudo apache2ctl configtest(Debian/Ubuntu)或 sudo httpd -t(CentOS/RHEL)sudo systemctl restart apache2(或 httpd)