Apache 缓存配置与优化
Apache Caching Configuration and Optimization
概述 (Overview)
缓存是提高Web应用性能和用户体验的关键技术。本文将详细介绍Apache中各种缓存机制的配置方法,包括浏览器缓存、代理缓存、磁盘缓存和内存缓存等核心技术。
Caching is a key technology for improving web application performance and user experience. This article will detail the configuration methods for various caching mechanisms in Apache, including browser caching, proxy caching, disk caching, and memory caching core technologies.
1. 浏览器缓存配置 (Browser Cache Configuration)
1.1 基本浏览器缓存头 (Basic Browser Cache Headers)
# 启用Expires模块
LoadModule expires_module modules/mod_expires.so
# 启用Headers模块
LoadModule headers_module modules/mod_headers.so
# 设置Expires头
<IfModule mod_expires.c>
ExpiresActive On
# 默认缓存时间
ExpiresDefault "access plus 1 month"
# HTML文件缓存1小时
ExpiresByType text/html "access plus 1 hour"
# CSS和JS文件缓存1年
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
# 图片文件缓存1年
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
# 字体文件缓存1年
ExpiresByType application/font-woff "access plus 1 year"
ExpiresByType application/font-woff2 "access plus 1 year"
ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
ExpiresByType font/truetype "access plus 1 year"
</IfModule>
1.2 Cache-Control头配置 (Cache-Control Header Configuration)
# 设置Cache-Control头
<IfModule mod_headers.c>
# HTML文件不缓存
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=3600, must-revalidate"
</FilesMatch>
# CSS和JS文件长期缓存
<FilesMatch "\.(css|js)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
# 图片文件长期缓存
<FilesMatch "\.(gif|jpe?g|png|ico)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
# 字体文件长期缓存
<FilesMatch "\.(woff|woff2|ttf|eot)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
# PDF文件短期缓存
<FilesMatch "\.pdf$">
Header set Cache-Control "max-age=86400, public"
</FilesMatch>
</IfModule>
2. 代理缓存配置 (Proxy Cache Configuration)
2.1 mod_cache基础配置 (mod_cache Basic Configuration)
# 启用缓存模块
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
# 基本缓存配置
<IfModule mod_cache.c>
# 启用缓存
CacheEnable disk /
# 设置缓存根目录
CacheRoot /var/cache/apache2/mod_cache_disk
# 设置缓存目录结构
CacheDirLevels 2
CacheDirLength 1
# 设置默认过期时间
CacheDefaultExpire 3600
# 设置最大过期时间
CacheMaxExpire 86400
# 设置最后修改时间因子
CacheLastModifiedFactor 0.1
</IfModule>
2.2 磁盘缓存详细配置 (Disk Cache Detailed Configuration)
<IfModule mod_cache_disk.c>
# 缓存存储配置
CacheRoot /var/cache/apache2/mod_cache_disk
CacheDirLevels 2
CacheDirLength 1
# 缓存大小限制
CacheMaxFileSize 1048576
CacheMinFileSize 1
# 缓存清理配置
CacheGcClean 0
CacheGcUnused 0
CacheGcInterval 30
# 缓存文件权限
CacheDirPerms 700
CacheFilePerms 600
</IfModule>
2.3 缓存控制头 (Cache Control Headers)
# 缓存控制配置
<IfModule mod_cache.c>
# 启用缓存头
CacheHeader on
# 启用锁机制防止缓存竞争
CacheLock on
CacheLockPath /tmp/mod_cache-lock
CacheLockMaxAge 5
# 忽略特定头信息
CacheIgnoreHeaders Set-Cookie
CacheIgnoreNoLastMod On
CacheIgnoreQueryString Off
</IfModule>
3. 内存缓存配置 (Memory Cache Configuration)
3.1 mod_cache_socache配置 (mod_cache_socache Configuration)
# 启用共享内存缓存模块
LoadModule cache_socache_module modules/mod_cache_socache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
<IfModule mod_cache_socache.c>
# 启用内存缓存
CacheEnable socache /
# 设置内存缓存大小
SocacheProvider shmcb:/var/cache/apache2/socache_shmcb(1024000)
# 内存缓存配置
CacheSocacheMaxSize 102400
CacheSocacheMinSize 1024
CacheSocacheReadSize 1024
CacheSocacheReadTime 10000
</IfModule>
3.2 混合缓存配置 (Hybrid Cache Configuration)
# 混合缓存配置(内存+磁盘)
<IfModule mod_cache.c>
# 小文件使用内存缓存
CacheEnable socache /static/small/
CacheSocacheMaxSize 51200
# 大文件使用磁盘缓存
CacheEnable disk /static/large/
CacheRoot /var/cache/apache2/mod_cache_disk
# 默认使用磁盘缓存
CacheEnable disk /
</IfModule>
4. 特定内容缓存 (Specific Content Caching)
4.1 静态文件缓存 (Static File Caching)
# 静态文件缓存优化
<Directory "/var/www/html/static">
# 启用ETag
FileETag MTime Size
# 设置缓存控制
<IfModule mod_headers.c>
Header set Cache-Control "max-age=31536000, public"
</IfModule>
# 启用压缩
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript
</IfModule>
</Directory>
4.2 动态内容缓存 (Dynamic Content Caching)
# 动态内容缓存配置
<Location "/api/">
# 短期缓存API响应
<IfModule mod_cache.c>
CacheEnable disk
CacheDefaultExpire 300
CacheMaxExpire 3600
</IfModule>
# 设置缓存控制头
<IfModule mod_headers.c>
Header set Cache-Control "max-age=300, public"
</IfModule>
</Location>
# CMS页面缓存
<LocationMatch "^/(news|blog)/">
<IfModule mod_cache.c>
CacheEnable disk
CacheDefaultExpire 1800
</IfModule>
</LocationMatch>
5. 缓存失效和更新 (Cache Invalidation and Updates)
5.1 基于文件修改时间的缓存 (File Modification Time Based Caching)
# 启用ETag和最后修改时间
<IfModule mod_headers.c>
FileETag MTime Size
# 对于频繁更新的内容
<FilesMatch "\.(html|php)$">
Header set Cache-Control "max-age=300, must-revalidate"
</FilesMatch>
</IfModule>
5.2 手动缓存清除 (Manual Cache Clearing)
# 缓存管理配置
<Location "/cache-manager">
SetHandler cache-manager
# 访问控制
<RequireAll>
Require ip 192.168.1.0/24
Require ip 127.0.0.1
</RequireAll>
</Location>
6. 缓存性能优化 (Cache Performance Optimization)
6.1 缓存大小优化 (Cache Size Optimization)
<IfModule mod_cache_disk.c>
# 优化缓存大小
CacheMaxFileSize 2097152 # 2MB
CacheMinFileSize 100 # 100 bytes
# 缓存目录优化
CacheDirLevels 3
CacheDirLength 2
# 垃圾回收优化
CacheGcClean 0
CacheGcUnused 1
CacheGcInterval 60
</IfModule>
6.2 缓存预热 (Cache Warming)
# 缓存预热脚本示例
# /usr/local/bin/cache-warm.sh
#!/bin/bash
WARM_URLS=(
"http://www.example.com/"
"http://www.example.com/products/"
"http://www.example.com/about/"
)
for url in "${WARM_URLS[@]}"; do
echo "Warming cache for: $url"
curl -s -o /dev/null "$url"
done
echo "Cache warming completed!"
7. 缓存监控和调试 (Cache Monitoring and Debugging)
7.1 缓存状态头 (Cache Status Headers)
# 添加缓存状态头用于调试
<IfModule mod_headers.c>
# 添加缓存命中状态
Header always set X-Cache-Status "%{CACHE_STATUS}e"
# 添加缓存存储位置
Header always set X-Cache-Store "%{CACHE_STORAGE}e"
</IfModule>
7.2 缓存日志配置 (Cache Log Configuration)
# 缓存日志格式
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %{CACHE_STATUS}e" cache_combined
# 缓存访问日志
CustomLog /var/log/apache2/cache_access.log cache_combined
# 缓存错误日志
ErrorLog /var/log/apache2/cache_error.log
LogLevel debug cache:trace6
7.3 缓存监控脚本 (Cache Monitoring Script)
#!/bin/bash
# cache-monitor.sh
monitor_cache() {
local cache_dir="/var/cache/apache2/mod_cache_disk"
echo "=== Cache Monitoring ==="
# 检查缓存目录状态
echo "1. Cache Directory Status:"
if [ -d "$cache_dir" ]; then
echo " Cache directory exists"
echo " Size: $(du -sh $cache_dir 2>/dev/null | cut -f1)"
echo " Files: $(find $cache_dir -type f 2>/dev/null | wc -l)"
else
echo " Cache directory not found"
fi
# 检查缓存命中率
echo
echo "2. Recent Cache Activity:"
tail -50 /var/log/apache2/cache_access.log | grep -c "HIT" && echo " cache hits" || echo "0 cache hits"
tail -50 /var/log/apache2/cache_access.log | grep -c "MISS" && echo " cache misses" || echo "0 cache misses"
# 检查缓存错误
echo
echo "3. Cache Errors:"
grep -i "cache\|error" /var/log/apache2/cache_error.log | tail -10
echo
echo "Cache monitoring completed!"
}
monitor_cache
8. 安全缓存配置 (Security Cache Configuration)
8.1 敏感数据缓存控制 (Sensitive Data Cache Control)
# 防止敏感数据被缓存
<Location "/admin/">
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "0"
</IfModule>
</Location>
<Location "/api/user/">
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, private"
</IfModule>
</Location>
8.2 缓存访问控制 (Cache Access Control)
# 缓存访问控制
<Directory "/var/cache/apache2">
# 防止直接访问缓存文件
Require all denied
# 或者限制特定IP访问
<RequireAll>
Require ip 127.0.0.1
Require ip 192.168.1.0/24
</RequireAll>
</Directory>
小结 (Summary)
通过本文学习,你应该掌握:
- Apache浏览器缓存头的配置方法
- mod_cache模块的启用和基本配置
- 磁盘缓存和内存缓存的详细配置
- 特定内容的缓存策略
- 缓存失效和更新机制
- 缓存性能优化技术
- 缓存监控和调试方法
- 安全缓存配置
缓存是提高Web应用性能的重要手段,正确配置缓存能够显著减少服务器负载并提升用户体验。在下一篇文章中,我们将详细介绍Apache压缩与静态文件优化技术。