LNMP缓存策略实战指南
一 整体思路与分层缓存
二 Nginx缓存配置
静态资源与浏览器缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header Vary Accept-Encoding;
}
location ~ \.php$ {
add_header Cache-Control "no-cache, must-revalidate";
expires off;
}
反向代理缓存 Proxy Cache(适用于 Nginx 作为反向代理/负载均衡)
http {
proxy_cache_path /var/cache/nginx
levels=1:2
keys_zone=backend_cache:10m
max_size=10g
inactive=60m
use_temp_path=off;
server {
location / {
proxy_pass http://backend;
proxy_cache backend_cache;
proxy_cache_key "$scheme$proxy_host$request_uri";
proxy_cache_valid 200 304 12h;
proxy_cache_valid 301 302 1h;
proxy_cache_valid any 1m;
proxy_cache_use_stale error timeout invalid_header http_500;
proxy_cache_min_uses 1;
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
add_header X-Proxy-Cache $upstream_cache_status;
}
}
}
FastCGI缓存 FastCGI Cache(适用于 PHP-FPM 动态页面)
http {
fastcgi_cache_path /var/cache/nginx
levels=1:2
keys_zone=php_cache:10m
max_size=1g
inactive=60m
use_temp_path=off;
server {
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_cache php_cache;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_min_uses 1;
fastcgi_cache_bypass $cookie_nocache $arg_nocache;
add_header X-FastCGI-Cache $upstream_cache_status;
}
}
}
三 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
APCu(用户态数据缓存,适合片段/配置/计数器等)
[apcu]
extension=apcu.so
apcu.enable=1
apcu.shm_size=64M
apcu.ttl=7200
Redis / Memcached(对象缓存,适合热点数据与会话)
# Ubuntu/Debian
sudo apt-get install redis-server php-redis
sudo apt-get install memcached php-memcached
sudo systemctl restart php7.4-fpm
四 MySQL缓存与数据库层优化
InnoDB 缓冲池(最核心的“缓存”)
查询缓存说明
五 上线与运维要点
缓存命中观测与调优
缓存失效与更新策略
安全与合规