CentOS 缓存加速网站访问技巧
一 分层缓存架构与适用场景
二 Nginx 与 Varnish 配置要点
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 {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
access_log off;
add_header Cache-Control "public, max-age=2592000";
}
vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "8080";
}
acl purge {
"localhost";
"127.0.0.1";
}
sub vcl_recv {
if (req.http.Cookie ~ "PHPSESSID" || req.http.Authorization) {
return (pass);
}
if (req.method == "PURGE") {
if (!client.ip ~ purge) { return (synth(403, "Forbidden")); }
return (purge);
}
return (hash);
}
sub vcl_backend_response {
if (bereq.http.Cookie ~ "PHPSESSID") {
set beresp.uncacheable = true;
return (deliver);
}
set beresp.grace = 30s;
}
sub vcl_deliver {
set resp.http.X-Cache = obj.hits > 0 ? "HIT" : "MISS";
}
sudo systemctl start varnish
sudo systemctl enable varnish
三 应用层与数据库缓存
sudo yum install memcached -y
sudo systemctl start memcached
sudo systemctl enable memcached
sudo yum install php74-php-pecl-memcached -y
sudo systemctl restart php74-php-fpm
sudo yum install libmemcached-tools -y
memcdump --servers=127.0.0.1:11211
sudo yum install redis -y
sudo systemctl start redis
sudo systemctl enable redis
[mysqld]
innodb_buffer_pool_size = 1G
四 操作系统与文件系统层优化
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5
vm.vfs_cache_pressure = 50
sudo sysctl -p
free -h
cat /proc/meminfo | grep "Cached"
echo "tmpfs /var/www/html/file_cache tmpfs defaults,noatime,size=8G 0 0" | sudo tee -a /etc/fstab
sudo mount -o remount /var/www/html/file_cache
以上做法有助于提升 I/O 密集型站点的响应速度与稳定性。五 CDN 加速与落地步骤