set up a cookie via varnish

3.3k views Asked by At

I'm running a Drupal 7 site using varnish 3.

We have 2 sites: the regular site(example.com) and the mobile site(m.example.com)

The current flow now is that when a user type the regular site through his mobile device he will be redirected to the mobile site directly.

We want to give the user the option to see the regular site also through his mobile device.

Long story short: How do we set a cookie through varnish(its important that the varnish will set it and not the application).

We tried this code:

sub_vcl{
  if (req.http.host ~ "^example\.com") {
    if (req.url ~   "^/(admissions|arts|aspaka|bog|cc|chemistry|GermanHistory|humanities|institutes|lifesci|peace|public-affairs)($|/)|~") {
      set req.backend = mondrian;
      set req.http.host = "exmpale.com";
    }
    else {
      if (req.http.cookie !~ "nomobi=true") {
        if (req.url ~ "nomobi=true") {
          set req.http.cookie = "nomobi=true";
        }
        else {
          call devicedetect;
          if (req.http.X-UA-Device ~ "^mobile" && req.url !~ "^/registration") {
            set req.http.location = "http://m.example.com" + req.url;
            error 750 ;
          }
        }
      }
    }
  }
}

but it doesn't work. Thanks!

1

There are 1 answers

2
NITEMAN On

You are setting a request cookie instead of a response cookie, so cookie is passed to the backend instead of the client.


WARNING:

Be careful when doing set req.http.cookie = "xxx" since you will overwrite request cookie and you can break session/authentication parts of Drupal.


Long story short, you'll need to add a Set-Cookie Header (beresp.http.set-cookie) on vcl_fetch or in vcl_deliver, something like:

...
if (req.http.cookie !~ "nomobi=true") {
  if (beresp.http.Set-Cookie) {
    set beresp.http.Set-Cookie = beresp.http.Set-Cookie + "nomobi=true; path=/; domain=your.cookie.domian.tld";
  } else {
    set beresp.http.Set-Cookie = "nomobi=true; path=/; domain=your.cookie.domian.tld";
  }
}
...

You'll have to verify that the Set-Cookie header is a valid one for your domain(s).