Cookie based caching on Varnish 4.0

If you need to do Cookie-based caching on Varnish 4.0, for example caching content by country selection, this is what you need to do:

Let’s assume our cookie is named: selectedCountry. At first, in sub vcl_recv you have to add:

# Country based caching (cookie)
set req.http.X-COOKIEHASH = "";
if (req.http.Cookie ~ "selectedCountry=") {
set req.http.X-COOKIEHASH = regsub(req.http.Cookie,"^.*?selectedCountry=([^;]*);*.*$", "\1");
return (hash);

And on vcl_hash:

sub vcl_hash {

This will ensure the cookie will pass along with the request. Please note that this is not a good idea for caching, but if you’re out of workarounds it may be a last resort solution.

Drupal aggregated Views: Sort by number of records AND alphabetically

Let’s say you need to have a view with the most used tags in your site. For this you would normally create a taxonomy term view, add a contextual filter for the term name, and sort by number of records so term aggregation will take place with the most used tags first.

Drupal: Aggregate by number of records in a taxonomy term view


So your view will generate the most used tags in your content. This is useful for a Tag Cloud implementation.

But what if you needed the aggregated terms to be sorted alphabetically? As you can see from the above screenshot, you can sort only in one of two ways; alphabetically or by number of records.

The following snippet takes care of this problem. Place it in a hook_prerender hook and it will sort the terms alphabetically after doing the aggregation by number of records.

* Implements hook_views_pre_render().
function MYMODULE_views_pre_render(&$view) {
  // Sort the aggregated views results alphabetically since the view won't allow it if we select to sort by .
  if ($view->name === 'view_name') {
    $taxonomy_term_data_node_name = array();
    foreach ($view->result as $key => $row) {
      $taxonomy_term_data_node_name[$key] = $row->taxonomy_term_data_node_name;
    array_multisort($taxonomy_term_data_node_name, SORT_ASC,SORT_NATURAL|SORT_FLAG_CASE, $view->result);

Obviously, you have to replace the MYMODULE with your custom module name and view_name with the machine name of your view.