在CentOS上通过缓存加速网站,可以采用以下几种方法:
sudo yum install varnish
编辑 /etc/varnish/default.vcl
文件,根据需要进行自定义配置。例如:
backend default {
.host = "127.0.0.1";
.port = "8080";
}
sub vcl_recv {
if (req.http.host ~ "example.com") {
return (hash);
}
}
sub vcl_fetch {
if (beresp.status == 200 && beresp.ttl > 3600s) {
set beresp.ttl = 3600s;
}
}
sudo systemctl start varnish
编辑 /etc/nginx/nginx.conf
文件,添加如下配置:
location / {
proxy_pass http://127.0.0.1:6081;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
sudo systemctl restart nginx
tmpfs是一种基于内存的文件系统,可以显著提高文件读写速度。编辑 /etc/fstab
文件,添加如下行:
/dev/shm /var/www/html/file_cache tmpfs defaults,noatime,size=8G 0 0
然后重新挂载:
sudo mount -o remount /var/www/html/file_cache
sudo yum install nginx
在 /etc/nginx/nginx.conf
文件中添加如下配置:
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_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
...
}
}
}
sudo systemctl restart nginx
通过这些方法,可以显著提高网站的访问速度和响应时间。