Ubuntu LNMP缓存策略实操指南
一 整体思路与层级
二 Nginx缓存配置
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
access_log off; # 可选:静态资源关闭日志
}
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/php8.1-fpm.sock; # 按实际版本调整
fastcgi_cache php_cache;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
fastcgi_cache_valid any 5m;
add_header X-FastCGI-Cache $upstream_cache_status; # HIT/MISS/BYPASS
}
}
}
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
max_size=1g inactive=60m use_temp_path=off;
server {
location / {
proxy_pass http://127.0.0.1:9000;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Proxy-Cache $upstream_cache_status;
}
}
}
三 PHP缓存配置
sudo apt update
sudo apt install php8.1-opcache
sudo systemctl restart php8.1-fpm
[opcache]
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
sudo apt install php-apcu
sudo systemctl restart php8.1-fpm
[apcu]
extension=apcu.so
apcu.enable_cli=0
apcu.shm_size=32M
sudo apt install memcached php-memcached
sudo systemctl enable --now memcached
# php.ini 中确保 extension=memcached.so
sudo apt install redis-server php-redis
sudo systemctl enable --now redis-server
# php.ini 中确保 extension=redis.so
四 MySQL缓存配置
SHOW ENGINE INNODB STATUS\G
# 命中率 = (1 - Innodb_buffer_pool_reads / Innodb_buffer_pool_read_requests) * 100%
SET GLOBAL innodb_buffer_pool_load_at_startup=ON;
SET GLOBAL innodb_buffer_pool_dump_at_shutdown=ON;
五 生效验证与运维要点