You are here

function fastly_exit in Fastly 7

Implements hook_exit().

Add cache-control headers to tell Fastly to cache content. We mimic the cache-control headers sent by Drupal core, by avoiding sending cache headers if the result is an error or if in maintenance mode.

File

./fastly.module, line 15
Fastly module.

Code

function fastly_exit() {

  // Avoid caching 404's and error pages.
  // To do this check the status header.
  $status = drupal_get_http_header("status");
  $is_error = preg_match('/^(4|5)/', $status);
  $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
  $no_store = drupal_strtolower(variable_get('fastly_non_cached', ''));
  if (drupal_page_is_cacheable() && !$is_error && !variable_get('maintenance_mode', 0) && !drupal_match_path($path, $no_store)) {
    drupal_add_http_header('Surrogate-Control', 'max-age=' . variable_get('fastly_ttl', '86400'));
  }
  else {
    drupal_add_http_header('Surrogate-Control', 'no-store');
  }
  drupal_add_http_header('Vary', 'Cookie,fastly-ssl');

  // Add Surrogate-Key headers based on path segments.
  // E.g. if the current path is product/some-category/product-name
  // we should end up with the following Surrogate-Keys:
  // product product/some-category product/some-category/product-name
  $path_segments = explode('/', drupal_get_path_alias());
  $surrogate_keys = array();
  $full_url = '';
  foreach ($path_segments as $segment) {
    if (empty($surrogate_keys)) {
      $full_url = $segment;
    }
    else {
      $full_url .= '/' . $segment;
    }
    $surrogate_keys[] = $full_url;
  }
  drupal_add_http_header('Surrogate-Key', implode(' ', $surrogate_keys));
}