LNMP架构下缓存策略可从Nginx、PHP、MySQL及辅助组件多层面优化,以下是关键策略及配置要点:
expires
指令设置浏览器缓存时间,减少重复请求。location ~* \.(jpg|css|js)$ {
expires 30d;
access_log off;
}
proxy_cache_path
定义缓存路径,proxy_cache_valid
设置不同状态码缓存时间。proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g;
location / {
proxy_cache my_cache;
proxy_cache_valid 200 10m;
}
fastcgi_cache
模块,设置缓存路径及过期策略。fastcgi_cache_path /var/cache/nginx/php levels=1:2 keys_zone=php_cache:10m;
location ~ \.php$ {
fastcgi_cache php_cache;
fastcgi_cache_valid 200 5m;
}
php.ini
中启用。opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
// Redis示例
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$data = $redis->get('cached_key') ?: fetchFromDB();
innodb_buffer_pool_size
建议设置为物理内存的60%-80%。[mysqld]
innodb_buffer_pool_size=4G
listen 443 ssl http2;
$upstream_cache_status
)。通过组合上述策略,可显著提升LNMP架构的响应速度和并发能力,降低后端负载。