当使用session_start()时,Varnish Cache不缓存PHP页面

时间:2011-02-23 01:39:45

标签: php caching session varnish

我第一次使用Varnish Cache 并且没有任何乐趣让我按照自己的意愿去工作。

我的问题似乎很简单。

我希望将.php页面缓存。

到目前为止,每个.php请求总是传递清漆 缓存并点击我的apache web服务器。

问题在于cookies和对session_start()的调用;

没有session_start()=缓存 使用session_start()=无缓存

现在文档很简单,可以理解 但我试过并尝试过失败。尽快 因为我添加了对session_start()=不再缓存的调用。

以下是带w / PHP的示例HTML:

<?php 
session_start(); 
?>

<html>
<head>
</head>
<body>  

<?php echo date('Y-m-d H-i-s'); ?>

</body>
</html>

这是我非常干净简单的清漆default.vcl

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

sub vcl_recv {
  unset req.http.Cookie;
  return (lookup);
}

sub vcl_fetch {
    if (beresp.http.Set-Cookie) {
        unset beresp.http.Set-Cookie;
        return (deliver);
    }
}

这应该取消客户端和服务器的Cookie 它确实似乎这样做了。使用FireBug进行调试时 在FireFox中,我可以看到Set-Cookie和Cookie HTTP标头 当我使用default.vcl

时不存在

以下是FireFox的HTTP标头:

响应标题:

HTTP/1.1 200 OK
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Type: text/html
Content-Length: 192
Date: Wed, 23 Feb 2011 01:34:17 GMT
X-Varnish: 2052563421
Age: 0
Via: 1.1 varnish
Connection: keep-alive

Request Headers:

GET /test.php HTTP/1.1
Host: xshare.com.local
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Cache-Control: max-age=0

我只是看不出我出错的地方。 我修改了2个小时,添加/更改和删除 .vcl配置文件的行和变体。

有人可以提供任何建议吗?

非常感谢。

2 个答案:

答案 0 :(得分:2)

正如您现在可能发现的那样,缓存和Cookie不匹配。您正在删除上述示例中的会话cookie(以及所有其他cookie),因此在使用Varnish时,您将无法使用会话。

你可以做两件事: - 允许cookie但不为登录用户提供缓存 - 除非你真的需要

,否则不要使用会话(或cookie)

第三个更复杂的解决方案是剥离大多数页面的cookie,但允许它们用于某些页面,然后将这些页面作为ESI块处理。关于这一点存在大量文档。

答案 1 :(得分:1)

我现在找到了一系列规则 使用session_start()缓存.php页面。

我已离开,但评论了其中一些 我一直在尝试。

试验和错误现在只有2个配置规则。

一个用于客户端,一个用于服务器。

Client = unset req.http.Cookie;

Server = set beresp.ttl = 5d;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

sub vcl_recv {
  unset req.http.Cookie;
#  unset req.http.Cache-Control;
  return (lookup); 
}

sub vcl_fetch {
     if (beresp.http.Set-Cookie) {
         set beresp.ttl = 5d;
#         unset beresp.http.Set-Cookie;
#         unset beresp.http.Expires;
#         unset beresp.http.Cache-Control;
         return (deliver);
     }
}

干杯。