Varnish Cookie Tweak to allow Anonymous Comments with Pressflow

Submitted by Janak on Wed, 12/29/2010 - 13:28

If you are using Drupal and have allowed anonymous user to leave comments on the site, you will notice that the core comments module adds two cookies named comment_info_name and comment_info_mail. These cookies allow the comments form to be auto populated with name and email on any subsequent comments from the same user.

For majority of users this is not something of a concern. Whist this is useful, if any cookies are passed back from client side in the request, Varnish will simply request the page from the back end instead of requesting the page from the cache. This will result in many cache MISSes as the cookie is set for 365 days (!!!!)

Code responsible for setting the comment cookies in Drupal

function comment_form_validate($form, &$form_state) {
  global $user;
  if ($user->uid === 0) {
    foreach (array('name', 'homepage', 'mail') as $field) {
      // Set cookie for 365 days.
      if (isset($form_state['values'][$field])) {
        setcookie('comment_info_'. $field, $form_state['values'][$field], time() + 31536000, '/');
      }
    }
  }
  comment_validate($form_state['values']);
}

Varnish VCL tweak to allow comment cookies whilst serving from cache

We can configure Varnish to not remove the cookie when receiving a request:

sub vcl_recv {
	// remove comment_info cookies
	set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(comment_info.+)=[^;]*", "");
 
	// Remove a ";" prefix, if present.
	set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
 
	// Remove empty cookies.
	if (req.http.Cookie ~ "^\s*$") {
			unset req.http.Cookie;
	}
}

This will allow the cookie to be set clientside but varnish will remove it when looking up the page in cache.

simplez...