Claude
Skills
Sign in
Back

cdn-media-delivery

Included with Lifetime
$97 forever

Use when configuring CDN for media delivery, implementing cache invalidation, or designing signed URL patterns. Covers CDN configuration, edge caching, origin shielding, and secure media access for headless CMS.

General

What this skill does


# CDN Media Delivery

Guidance for configuring CDN delivery, cache management, and secure media access for headless CMS architectures.

## When to Use This Skill

- Configuring CDN for media delivery
- Implementing cache invalidation strategies
- Setting up signed/secure URLs
- Optimizing edge caching
- Configuring origin shielding

## CDN Architecture

### Basic CDN Setup

```text
┌─────────────────────────────────────────────────────────────┐
│                         Users                                │
│              (Global, geographically distributed)            │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                      CDN Edge Network                        │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐        │
│  │ Edge    │  │ Edge    │  │ Edge    │  │ Edge    │        │
│  │ US-West │  │ US-East │  │ Europe  │  │ Asia    │        │
│  └─────────┘  └─────────┘  └─────────┘  └─────────┘        │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                      Origin Shield                           │
│              (Optional intermediate cache layer)             │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                      Origin Server                           │
│  ┌───────────────┐  ┌────────────────┐  ┌───────────────┐  │
│  │ Media API     │  │ Blob Storage   │  │ Image         │  │
│  │ (transform)   │  │ (Azure/S3)     │  │ Processor     │  │
│  └───────────────┘  └────────────────┘  └───────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

## CDN Configuration

### Azure CDN (Front Door)

```csharp
// appsettings.json
{
  "Cdn": {
    "Provider": "AzureFrontDoor",
    "Endpoint": "https://media.example.com",
    "OriginHost": "storage.blob.core.windows.net",
    "CacheRules": {
      "Images": {
        "CacheDuration": "365.00:00:00",
        "QueryStringCaching": "IgnoreQueryString"
      },
      "Transforms": {
        "CacheDuration": "30.00:00:00",
        "QueryStringCaching": "UseQueryString"
      }
    }
  }
}
```

### CloudFront Configuration

```csharp
public class CloudFrontConfiguration
{
    public string DistributionId { get; set; } = string.Empty;
    public string DomainName { get; set; } = string.Empty;
    public string OriginId { get; set; } = string.Empty;

    public CacheBehavior DefaultCacheBehavior { get; set; } = new()
    {
        ViewerProtocolPolicy = "redirect-to-https",
        CachePolicyId = "658327ea-f89d-4fab-a63d-7e88639e58f6", // CachingOptimized
        Compress = true,
        AllowedMethods = new[] { "GET", "HEAD", "OPTIONS" },
        CachedMethods = new[] { "GET", "HEAD" }
    };

    public CacheBehavior[] CacheBehaviors { get; set; } =
    {
        new()
        {
            PathPattern = "/media/transform/*",
            CachePolicyId = "custom-transform-policy",
            QueryStringCaching = QueryStringCaching.All
        }
    };
}
```

### Cloudflare Configuration

```csharp
public class CloudflareConfiguration
{
    public string ZoneId { get; set; } = string.Empty;
    public string ApiToken { get; set; } = string.Empty;

    public PageRule[] PageRules { get; set; } =
    {
        new()
        {
            Targets = new[] { "*example.com/media/*" },
            Actions = new PageRuleAction
            {
                CacheLevel = "cache_everything",
                EdgeCacheTtl = 2592000, // 30 days
                BrowserCacheTtl = 86400  // 1 day
            }
        }
    };
}
```

## Cache Headers

### Setting Cache Headers

```csharp
public class MediaCacheMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        await next(context);

        if (context.Request.Path.StartsWithSegments("/media"))
        {
            var cacheControl = GetCacheControl(context.Request.Path);
            context.Response.Headers["Cache-Control"] = cacheControl;
            context.Response.Headers["Vary"] = "Accept, Accept-Encoding";
        }
    }

    private string GetCacheControl(PathString path)
    {
        // Original media: cache for 1 year (immutable content)
        if (path.Value?.Contains("/original/") == true)
        {
            return "public, max-age=31536000, immutable";
        }

        // Transformed images: cache for 30 days
        if (path.Value?.Contains("/transform/") == true)
        {
            return "public, max-age=2592000, stale-while-revalidate=86400";
        }

        // Default: 1 day
        return "public, max-age=86400";
    }
}
```

### Cache-Control Directives

| Directive | Purpose | Example |
| --------- | ------- | ------- |
| `public` | Allow CDN caching | Images, static assets |
| `private` | Browser only | User-specific content |
| `max-age` | Cache duration (seconds) | `max-age=86400` (1 day) |
| `immutable` | Never revalidate | Versioned assets |
| `stale-while-revalidate` | Serve stale while fetching | Background refresh |
| `no-cache` | Always revalidate | Dynamic content |
| `no-store` | Never cache | Sensitive data |

## Cache Invalidation

### Invalidation Service

```csharp
public interface ICdnInvalidationService
{
    Task InvalidatePathAsync(string path);
    Task InvalidatePathsAsync(IEnumerable<string> paths);
    Task InvalidatePrefixAsync(string prefix);
    Task InvalidateAllAsync();
}

// Azure CDN implementation
public class AzureCdnInvalidationService : ICdnInvalidationService
{
    private readonly CdnManagementClient _cdnClient;

    public async Task InvalidatePathAsync(string path)
    {
        await _cdnClient.Endpoints.PurgeContentAsync(
            _resourceGroup,
            _profileName,
            _endpointName,
            new PurgeParameters(new[] { path }));
    }

    public async Task InvalidatePrefixAsync(string prefix)
    {
        await _cdnClient.Endpoints.PurgeContentAsync(
            _resourceGroup,
            _profileName,
            _endpointName,
            new PurgeParameters(new[] { $"{prefix}/*" }));
    }
}

// CloudFront implementation
public class CloudFrontInvalidationService : ICdnInvalidationService
{
    private readonly AmazonCloudFrontClient _client;

    public async Task InvalidatePathAsync(string path)
    {
        var request = new CreateInvalidationRequest
        {
            DistributionId = _distributionId,
            InvalidationBatch = new InvalidationBatch
            {
                CallerReference = Guid.NewGuid().ToString(),
                Paths = new Paths
                {
                    Items = new List<string> { path },
                    Quantity = 1
                }
            }
        };

        await _client.CreateInvalidationAsync(request);
    }
}
```

### Event-Based Invalidation

```csharp
public class MediaUpdatedHandler : INotificationHandler<MediaUpdatedEvent>
{
    private readonly ICdnInvalidationService _cdn;

    public async Task Handle(MediaUpdatedEvent notification, CancellationToken ct)
    {
        // Invalidate original
        await _cdn.InvalidatePathAsync($"/media/{notification.MediaId}");

        // Invalidate all transformations
        await _cdn.InvalidatePrefixAsync($"/media/transform/{notification.MediaId}");
    }
}
```

## Signed URLs

### Signed URL Generation

```csharp
public class SignedUrlService
{
    public string GenerateSignedUrl(
        string path,
        TimeSpan validity,
        SignedUrlOptions? options = null)
    {
        options ??= new SignedUrlOptions();

        var expiry = DateTime.UtcNow.Add(validity);
        var expiryTimestamp =

Related in General