<% @asset_pipeline_prefixes.each do |prefix| %>
  location ^~ /<%= prefix %>/ {
    # Set expires headers for assets
    # Assets with a digest (32+ char hex string in filename) get max expires
    # Non-digest assets get 30 mins
    expires 30m;
    add_header Cache-Control public;
    gzip_static on;

    location ~ "-[0-9a-f]{32,}\." {
      expires max;
      add_header Cache-Control "public, immutable";

      # Set CORS allow origin for fonts only
      location ~* \.(eot|otf|ttf|woff|woff2)$ {
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "origin, authorization";
      }
    }

  }
<% end %>

<%= @nginx_extra_config %>

<% @asset_pipeline_prefixes.each do |prefix| %>
  location ^~ /<%= prefix %>/ {
    # Set expires headers for assets
    # Assets with a digest (32+ char hex string in filename) get max expires
    # Non-digest assets get 30 mins
    expires 30m;
    add_header Cache-Control public;
    gzip_static on;

    location ~ "-[0-9a-f]{32,}\." {
      expires max;
      add_header Cache-Control "public, immutable";
      add_header Surrogate-Key "assets assets-<%= @vhost %>";

      # Set CORS allow origin for fonts only
      location ~* \.(eot|otf|ttf|woff|woff2)$ {
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "origin, authorization";
      }
    }

  }
<% end %>

<%= @nginx_extra_config %>

Include surrogate keys for immutable assets
Include surrogate keys for immutable assets

As these assets are cached for perpetuity it is hard to make any changes
to how the CDN hosts them without needing to manually purge lots of
assets from the CDN or purge the entire CDN.

This was a problem we hit when enabling Brotli compression at the CDN,
where we were faced with this challenge of purging everything or a lot
of manual purges.

In order to try avoid this problem in future a surrogate key is being
set for both all application assets (assets) or an individual
applications ones based on the vhost (assets-government-frontend). These
surrogate keys can be used to purge a grouping of files from a Fastly
cache [1]. Thus, should we need to purge all assets (or an applications
assets), from the Fastly cache it will be a simple operation.

This is only applied to assets with a max expires time as these are the
items that are hard to remove from a cache, other times (with more
manageable cache times such as 30 mins) will clear by themselves in that
time frame.

[1]: https://docs.fastly.com/en/guides/getting-started-with-surrogate-keys
