apache源码编译需显式启用mod_deflate、mod_expires、mod_cache等核心模块,并验证其静态/动态加载状态,再通过配置实现压缩、缓存与头部控制,否则优化无效。

Apache 源码编译时开启压缩与缓存模块,关键不是“编译出更快的二进制”,而是确保核心性能模块被静态或动态加载,并在运行时正确启用。Apache 本身不执行 PHP/Python 等动态逻辑,它的优化价值体现在:减少传输体积(压缩)、复用连接(KeepAlive)、避免重复生成(服务端缓存)。这些能力必须在编译阶段就纳入,否则配置再细也无效。
编译前确认依赖模块已启用
mod_deflate(压缩)、mod_expires / mod_cache(缓存)、mod_headers(配合缓存头)是基础组合。编译时需显式添加对应参数:
启用 deflate 压缩支持
--enable-deflate
这是启用 Gzip 压缩的前提。若漏掉,后续所有 AddOutputFilterByType 配置都无效。启用缓存相关模块
--enable-expires(控制 Expires 头)--enable-cache+--enable-file-cache或--enable-disk-cache(磁盘缓存)--enable-mem-cache(内存缓存,需搭配 --enable-cache)
注意:mod_cache 是抽象层,实际缓存需搭配 file/disk/mem 子模块。启用 headers 和 filter(辅助模块)
--enable-headers(设置 Cache-Control、Vary 等响应头)--enable-filter(mod_deflate 依赖此模块做内容过滤)
示例完整 configure 命令:
./configure \ --prefix=/usr/local/apache \ --enable-so \ --enable-rewrite \ --enable-deflate \ --enable-expires \ --enable-cache \ --enable-disk-cache \ --enable-headers \ --enable-filter \ --with-mpm=event
编译后必须验证模块是否真正加载
光编译进去不等于运行时生效。启动前务必检查:
- 执行
httpd -M | grep -E "(deflate|expires|cache|headers|filter)"
应看到类似输出:deflate_module (static)expires_module (static)cache_module (static)disk_cache_module (static)headers_module (static)filter_module (static)
若显示 (shared),说明是动态模块,还需确认 LoadModule 行已在 httpd.conf 中启用(如 LoadModule deflate_module modules/mod_deflate.so)。
配置阶段才是性能落地的关键
模块编译进去了,但默认不工作。需在 httpd.conf 或虚拟主机配置中补充实际规则:
-
压缩文本类响应
Apache Superset Dashboard and SQL Exploration Skill下载Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
<ifmodule mod_deflate.c> SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|pdf|zip|mp3|mp4|swf)$ no-gzip AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json Header append Vary Accept-Encoding </ifmodule>
-
为静态资源设缓存头
<ifmodule mod_expires.c> ExpiresActive on ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/png "access plus 1 month" </ifmodule>
-
对可缓存的动态响应启用 disk 缓存
<ifmodule mod_cache.c> CacheQuickHandler off <ifmodule mod_disk_cache.c> CacheRoot "/usr/local/apache/cache" CacheEnable disk / CacheIgnoreHeaders Set-Cookie CacheIgnoreCacheControl On </ifmodule></ifmodule>注意:需提前创建
/usr/local/apache/cache目录并赋权(chown -R daemon:daemon cache)。
绕不开的细节提醒
- 不要同时开启 PHP 的
zlib.output_compression = On,它会与 mod_deflate 冲突,导致响应损坏或无压缩; -
KeepAlive On要配合理 Timeout(建议 5–7 秒)和 MaxKeepAliveRequests(建议 100–200),这对动态页面多请求场景(如 AJAX 加载仪表盘)影响显著; - 若后端已用 Nginx 做反向代理,Apache 层 KeepAlive 可设为 Off,由 Nginx 统一管理长连接;
- 缓存动态内容前,先确认业务允许几秒/几分钟的 stale 时间——用户中心页缓存 5 秒通常安全,支付回调页则不能缓存。
不复杂但容易忽略。










