简体   繁体   中英

Serve different varnish cache for the same page based on a value in cookie?

This question might not make sense at all since I'm new to varnish but here it is:

I'm building a commerce site with multi currency support and the pages are served by varnish. Everytime the currency changes, it changes the cookie according to the new currency, and since the cookie in requested header changes, will it make varnish to create a different cache? I need to serve new content if the currency value changes to show the correct product price.

In case varnish does not refresh as mentioned above, can this be achieved by varnish configuration to cache different content for different currency value inside the cookie or modifying the page header in some way?

First, sorry for the (very) late answer. hope it will help you!

The easiest way is not to cache the home page, and redirect from it with PHP or with apache's or nginx's mod_rewrite.

Step 1 - dont cache the homepage

varnish

default.vcl

sub vcl_recv {
    ...

    # dont cache the homepage
    if (req.url ~ "^/") {
        return(pass);
    }

    ...
}

Remember to restart varnish after any change.

Step 2 - redirect to currency's page

Here, choose one of the following, to redirect.

1. PHP

(Lets say that the currency cookie named "cry")

index.php

if (!empty($_COOKIE["cry"]))
{
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://www.yourdomain.co.uk/?currency=".$_COOKIE["cry"]); 
}

2. nginx

(Again, Lets say that the currency cookie named "cry")

yoursite file in sites-enabled - nginx

server {
    listen       80;
    server_name  bestsellers.co.uk www.bestsellers.co.uk;

    location = / {
        if ($cookie_cry ~* "usdollars") {
            rewrite ^ http://www.yourdomain.co.uk/?currency=usd permanent;
        }
        if ($cookie_cry ~* "ilshekels") {
            rewrite ^ http://www.yourdomain.co.uk/?currency=ils permanent;
        }
        if ($cookie_cry ~* "rusruble")  {

        ... and more ...
    }

    ...
}

Remember to restart nginx after any change.

3. apache2

I dont really know how to do this in apache, but google can help you.'


And you should be fine. http://www.yourdomain.com/?currency=usd will be other than http://www.yourdomain.com/?currency=ils . If you have any questions, comment here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM