发布于2026-07-20 阅读(0)
扫一扫,手机访问
Apache静态资源优化实操指南
说到Apache的性能调优,静态资源这块儿其实是最容易出效果、也最容易被忽视的环节。很多运维同学一上来就怼内存、调内核参数,结果发现浏览器缓存压根没配,压缩也没开,白白浪费了服务器资源。今天咱们就把这几个核心优化点掰开揉碎,说清楚每一步怎么配、怎么验证,顺便把那些容易踩的坑也指出来。
压缩是减少传输体积最直接的手段,但有个前提:别对已经压缩过的图片再动手。
sudo a2enmod deflate;CentOS/RHEL 确认 mod_deflate 已安装。/etc/apache2/mods-enabled/deflate.conf 或 httpd.conf):# 压缩文本与脚本类资源
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css \
application/ja vascript application/x-ja vascript 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
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5curl -I 看响应头里有没有 Content-Encoding: gzip。缓存策略直接决定了用户回访时的加载速度。强缓存(一年)给带指纹的资源,协商缓存(每次都问服务器)给 HTML 和 JSON,这是业界通行的做法。
sudo a2enmod expires headers;CentOS/RHEL 确认 mod_expires 与 mod_headers 已加载。# 1) 使用 Expires 模块设置 Expires 与 Cache-Control
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/ja vascript "access plus 1 month"
ExpiresByType application/x-ja vascript "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 year"
# 2) 用 Headers 精细控制
# 对带指纹/版本号的资源设置“强缓存”
Header set Cache-Control "public, max-age=31536000, immutable"
# 对可能频繁变动的资源设置“协商缓存”
Header set Cache-Control "public, max-age=0, must-revalidate"
access plus 1 month、now plus 30 days、A2592000(从访问时计算)modification plus 5 hours 3 minutes、M604800(从文件最后修改时间计算,M 仅对静态文件有效)Cache-Control: max-age=… 与 Expires,以及 Vary: Accept-Encoding。HTTP/2 的多路复用能让一个连接同时处理多个请求,配合 CDN 分发,效果立竿见影。
sudo a2enmod http2(Debian/Ubuntu);编译时加入 --enable-http2(源码)。
Protocols h2 http/1.1
前端资源和后端配置两手都要硬。资源本身不够轻,再好的缓存策略也帮不上忙。
app.a1b2c3.js)解决强缓存更新问题。a2dismod ),降低内存占用与攻击面。配置写完了,怎么确认生效?怎么排查问题?这里给出几个常用命令和要点。
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)Vary: Accept-Encoding,确保 CDN/浏览器 能正确区分并缓存压缩与非压缩版本。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8