About response header and request header condition

Michael Alger varnish at mm.quex.org
Thu Feb 23 08:22:20 CET 2012

On Thu, Feb 23, 2012 at 03:29:42PM +0900, Jewel Nuruddin wrote:
> in my VCL configuration
> sub vcl_recv {
> ### pass if http hearder response is "SMARTPHONE:1"
>           if (req.http.SMARTPHONE ~ "1") {
>                 return (pass);
>                 }
> }
> in my page I set the above header response so if the responses match it
> will not cache
> but it always cache? can some one help me why ?

The "req" object refers to the headers sent in the client request.
It's unlikely the browser on any device sends a header named
"SMARTPHONE", so that's the reason it won't be matching.

> One more question, can varnish identified for caching or not caching both
> in http header "response" and "request"?

Yes it can. The response object is generally called "beresp". However
you can't access it in vcl_recv, since vcl_recv is called when the
client request is initially received - there hasn't been a response
from the backend at this point. vcl_recv is used to rewrite the
request and tell Varnish whether it should try to look up the object
in cache or go direct to the server, as well as selecting which
backend to use. When you return (lookup) you instruct Varnish to look
the object up in its cache, and if it fails to try to fetch it from
the backend.

You'll therefore want to make your determination as to whether or not
to cache the response in vcl_fetch, which is called immediately after
Varnish has fetched an object from the backend server. From here you
can access the "beresp" object and decide whether or not you want to
cache the response based on any attribute of it, including the
response HTTP headers.


It will still be possible for smartphones to have a page served to
them from the cache. For example if the index page of www.example.com
returns different content based on the user-agent, if a regular
(non-smartphone) browser accesses the site, Varnish will cache the
response. If a phone then requests it, Varnish will just serve the
previously generated response from its cache. This is because you
haven't told Varnish that requests from "smartphones" need to be
treated differently - only that responses sent to a device the backend
identified as a smartphone should not be cached.

If you're able to, I'd suggest moving whatever logic the backend uses
to determine if a device is a smartphone out of the backend and into
Varnish, using VCL if possible. This way, Varnish can determine what
it's supposed to do with the request, serving everything it can from
cache and only going to the backend if it really needs to.

If the determination can _only_ happen on the backend, then you're
going to be forced to send every request that might _possibly_ be from
a smartphone or other "special" device back to the backend, largely
negating the benefits of having Varnish in the first place.

More information about the varnish-misc mailing list