CentOS LNMP 缓存优化实操指南
一 优化总览与优先级
二 Nginx 缓存优化
location ~* \.(js|css)$ {
expires 1y;
add_header Cache-Control "public, immutable";
etag on;
access_log off;
}
location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public";
access_log off;
}
http {
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=fcgi_cache:128m
max_size=10g 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-fpm.sock;
fastcgi_cache fcgi_cache;
fastcgi_cache_key "$scheme$request_method$host$request_uri$arg_v";
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
fastcgi_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
fastcgi_cache_lock on;
fastcgi_cache_background_update on;
add_header X-Cache-Status $upstream_cache_status;
proxy_cache_bypass $http_pragma;
proxy_no_cache $http_authorization;
}
}
}
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=proxy_cache:128m
max_size=10g inactive=60m use_temp_path=off;
server {
location / {
proxy_pass http://backend;
proxy_cache proxy_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating;
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status;
proxy_cache_bypass $http_cache_control;
}
}
}
三 PHP 缓存优化
[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]
extension=apcu.so
apcu.enable=1
apcu.shm_size=64M
四 MySQL 缓存优化
[mysqld]
innodb_buffer_pool_size=12G
innodb_buffer_pool_instances=8
innodb_buffer_pool_load_at_startup=ON
innodb_buffer_pool_dump_at_shutdown=ON
五 监控与压测闭环
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
wrk -t12 -c100 -d30s --latency http://your-domain.com/