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 *$ (清除所有緩存)
總結
以上是生活随笔為你收集整理的Varnish使用小结的全部內容,希望文章能夠幫你解決所遇到的問題。