TransWikia.com

Redirection in varnish based on cookie value

Server Fault Asked on January 30, 2021

We have varnish sitting in front of our site and it is imperative that we cache as much as possible.

Recently we decided to ditch GeoIP redirection for interstate content for a more traditional ‘choose your location’ page. This page sets a cookie for their ‘default’ location and the desired outcome would be to have varnish read this cookie and redirect when at ‘/’ only.

This functionality (while a little hacky) is supposed to be supported in varnish, but we’ve been unsuccessful in getting it to work. Should it work? Are we doing anything we shouldn’t be?

Next to having an uncached static HTML page, what are our other options here? Can we have something other than varnish sit in front of just that page?

When we deployed the change without varnish caching it, we had massive performance issues as the site is built on Drupal and had to bootstrap every load.

If it is established that Varnish should do what we want, I’ll add some vcl config to this question.

EDIT It looks like the best option is going to be to get varnish to not cache ‘/’ and handle the cookie-based redirection in Apache.

RewriteCond %{REQUEST_URI} ^/?$
RewriteCond %{HTTP_COOKIE} cookie_name=([^;]+)
RewriteRule .* http://site/%1 [R=301,L]

Seems to do what we need.

One Answer

This can be perfectly achieved on Varnish, more or less:

sub vcl_recv {
  if ( req.http.cookie ~ "cookie_name") {
    error 751 "http://site" + req.url;
  }
}
sub vcl_error {
  if (obj.status == 751) {
    /* Get new URL from the response */
    set obj.http.Location = obj.response;
    /* Set HTTP 301 for permanent redirect */
    set obj.status = 301;
    return(deliver);
  }
}

Answered by NITEMAN on January 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP