三 、配置一个简单的Varnish实例
由于版本的不同,Varnish配置文件的写法也存在一定差异,varnish2.x版本和1.x版本之间不但配置文件写法不同,而且新的版本功能也增加很多,并且去除了很多应用BUG,这里讲述的版本是varnish2.1.2,配置文件写法也以varnish2.x版本为基准。
Varnish安装完成后,默认的配置文件为/usr/local/varnish/etc/varnish/default.vcl,此文件内容默认全部被注释掉了,这里,我们以这个文件为模板,创建一个新的文件vcl.conf,并且放到/usr/local/varnish/etc目录下,配置完成的vcl.conf文件如下:
#通过backend定义了一个名称为webserver的后端主机,“.host”指定后端主机的IP地址或者域名,“.port”指定后端主机的服务端口。其中,“192.168.12.26”就是后端的一个web服务器。
1 backend webserver {
2 .host = "192.168.1.26";
3 .port = "80";
4 }
5
6 sub vcl_recv {
7 if (req.http.x-forwarded-for) {
8 set req.http.X-Forwarded-For =
9 req.http.X-Forwarded-For ", " client.ip;
10 } else {
11 set req.http.X-Forwarded-For = client.ip;
12 }
13
14 if (req.request != "GET" &&
15 req.request != "HEAD" &&
16 req.request != "PUT" &&
17 req.request != "POST" &&
18 req.request != "TRACE" &&
19 req.request != "OPTIONS" &&
20 req.request != "DELETE") {
21 return (pipe);
22 }
23
24 if (req.request != "GET" && req.request != "HEAD") {
25 return (pass);
26 }
27
28 if (req.http.host ~ "^(.*).ixdba.net" || req.http.host ~ "^(.*).ixdba.cn") {
29 set req.backend = webserver;
30 }
31
32 if (req.url ~ "\.(jsp|do)($|\?)") {
33 return (pass);
34 } else {
35 return (lookup);
36 }
37 }
38
39 sub vcl_pipe {
40 return (pipe);
41 }
42
43 sub vcl_pass {
44 return (pass);
45 }
46
47 sub vcl_hash {
48 set req.hash += req.url;
49 if (req.http.host) {
50 set req.hash += req.http.host;
51 } else {
52 set req.hash += server.ip;
53 }
54 return (hash);
55 }
56
57 sub vcl_hit {
58 if (!obj.cacheable) {
59 return (pass);
62 }
63
64 sub vcl_miss {
65 return (fetch);
66 }
67
68 sub vcl_fetch {
69 if (!beresp.cacheable) {
70 return (pass);
71 }
72 if (beresp.http.Set-Cookie) {
73 return (pass);
74 }
75
76 if (req.url ~ "^/servlet/") {
77 return (pass);
78 }
79
80 if (req.url ~ "^/services/") {
81 return (pass);
82 }
83
84 if (req.request == "GET" && req.url ~ "^/upload(.*)$") {
85 set beresp.ttl = 300s;
86 }
87
88 if (req.request == "GET" && req.url ~ "\.(png|xsl|xml|pdf|ppt|doc|docx|chm|rar|zip|bmp|jpeg|swf|ico|mp3|mp4|rmvb|ogg|mov
|avi|wmv|swf|txt|png|gif|jpg|css|js|html|htm)$") {
89 set beresp.ttl = 600s;
90 }
91 return (deliver);
92 }
93
94 sub vcl_deliver {
95 if (obj.hits > 0) {
96 set resp.http.X-Cache = "HIT from www.ixdba.net";
97 } else {
98 set resp.http.X-Cache = "MISS from www.ixdba.net";
99 }
100 return (deliver);
101 }