Varnish使用小结

文章原始出处和作者信息及 本声明
http://iyubo.blogbus.com/logs/35085709.html

此日志会随时更新,当然,是随着我的应用积累:)

实现静态文件压缩

Varnish itself does not compress or decompress objects, although that has been on our wish list for quite a while. However, it will operate correctly with backends that support compression.

从官方网站可以得知,Varnish本身并不能提供压缩的功能,但是我们又想要使用压缩,该怎么处理呢?(有关压缩的方面可以参考官方网站http://varnish.projects.linpro.no/wiki/FAQ/Compression

在vcl_recv中加入如下配置,为Varnish指定压缩算法,提高效率。(Even though there are few possible values for Accept-Encoding, Varnish treats them literally rather than semantically, so even a small difference which makes no difference to the backend can reduce cache efficiency by making Varnish cache too many different versions of an object.)

if (req.http.Accept-Encoding) {
if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
# No point in compressing these
remove req.http.Accept-Encoding;
} else if (req.http.Accept-Encoding ~ "gzip") {
set req.http.Accept-Encoding = "gzip";
} else if (req.http.Accept-Encoding ~ "deflate") {
set req.http.Accept-Encoding = "deflate";
} else {
# unkown algorithm
remove req.http.Accept-Encoding;
}
}

在vcl_hash中

sub vcl_hash {
set req.hash += req.url;
if (req.http.Accept-Encoding ~ "gzip") {
set req.hash += "gzip";
}
else if (req.http.Accept-Encoding ~ "deflate") {
set req.hash += "deflate";
}
hash;
}

这样就把压缩的工作还是交给后端服务器去做

添加一个Header标识是否命中

sub vcl_deliver {
        if (obj.hits > 0) {
                set resp.http.X-Cache = "HIT";
        } else {
                set resp.http.X-Cache = "MISS";
        }
}

对特定URL进行IP访问限制

如果我们对某些特定的URL只想某些IP能访问,又该怎么办呢?

首先定义允许访问的IP列表

acl permit {
"10.1.1.5";
"10.0.2.5";
"10.10.1.3";
}

然后是针对URL进行访问控制

if (req.url ~ "/test/.*" && !client.ip ~ permit) {
error 403 "Not Allowed.";
}

对特定URL不缓存

sub vcl_fetch {
if (req.request == "GET" && req.url ~ "/test/.*") {
set obj.ttl = 0s;
}
else {
set obj.ttl = 1800s;
}
#set obj.http.X-Varnish-IP = server.ip;
set obj.http.Varnish = "Tested by Kevin";
insert;
}

清除指定缓存内容

我们可以通过varnishadm这个命令从管理端口进行指定缓存的清除

/usr/varnish/bin/varnishadm -T 127.0.0.1:3500 url.purge /test/*

/usr/varnish/bin/varnishadm -T 127.0.0.1:3500 url.purge *$ (清除所有缓存)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值