Ubuntu LAMP 缓存机制配置指南
一 架构与总体思路
二 Apache HTTP 服务器缓存
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /static/
CacheRoot /var/cache/apache2/mod_cache_disk
CacheDirLevels 2
CacheDirLength 1
CacheDefaultExpire 3600
CacheMaxExpire 86400
CacheIgnoreHeaders Set-Cookie
</IfModule>
</IfModule>
<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/svg+xml "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>
三 PHP 运行时缓存
OPcache(必选,加速字节码执行)
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=0 ; 生产环境建议关闭 CLI,避免开发/CLI 干扰
APCu(用户空间对象缓存,适合单机数据缓存)
[apcu]
extension=apcu.so
apcu.enable=1
apcu.shm_size=64M
apcu.ttl=7200
apcu.enable_cli=0
Memcached/Redis(分布式/复杂对象缓存,二选一或并用)
四 MySQL/MariaDB 层缓存
InnoDB 缓冲池(核心,优先调大)
[mysqld]
innodb_buffer_pool_size=2G
innodb_buffer_pool_instances=8
innodb_log_file_size=256M
查询缓存说明
MyISAM 键缓存(如仍使用 MyISAM)
五 前端与全站加速
Varnish 反向代理缓存(示例)
backend default {
.host = "127.0.0.1";
.port = "80";
}
sub vcl_recv {
if (req.http.Cookie ~ "PHPSESSID" || req.http.Authorization) {
return (pass);
}
return (hash);
}
sub vcl_backend_response {
set beresp.ttl = 300s;
return (deliver);
}
CDN 与浏览器缓存
六 验证与运维要点
验证方法
安全与注意事项