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架構的響應速度和并發能力,降低后端負載。