How to Setup Caching on Caddy

A comprehensive guide to configuring caching and compression in Caddy for optimal performance.

Prerequisites

Before configuring caching on Caddy, ensure you have:

  • Caddy 2.x installed and running
  • Access to edit Caddyfile
  • Basic understanding of HTTP caching concepts
  • Root or sudo access to the server

Basic Caching Configuration

Cache Configuration
example.com {
    file_server
    
    # Enable caching for static files
    header {
        Cache-Control "public, max-age=31536000"
    }
    
    # Cache different file types
    @static {
        path *.css *.js *.jpg *.jpeg *.png *.gif *.ico *.webp
    }
    header @static {
        Cache-Control "public, max-age=31536000"
    }
    
    # HTML files with shorter cache
    @html {
        path *.html *.htm
    }
    header @html {
        Cache-Control "public, max-age=3600"
    }
}

Key directives explained:

  • file_server: Enables static file serving
  • header: Sets response headers
  • @matcher: Defines path matching rules

Cache-Control Headers

Advanced Cache Control
example.com {
    # Static assets with long cache
    @assets {
        path *.css *.js *.jpg *.jpeg *.png *.gif
    }
    header @assets {
        Cache-Control "public, max-age=31536000, immutable"
    }

    # Dynamic content with no cache
    @dynamic {
        path /api/* /admin/*
    }
    header @dynamic {
        Cache-Control "no-store, no-cache, must-revalidate"
        Pragma "no-cache"
    }
}

Compression Settings

example.com {
    encode gzip zstd
    
    # Custom compression for specific types
    @compress {
        path *.html *.css *.js *.json *.xml *.svg
    }
    encode @compress gzip zstd {
        minimum_length 1024
        level 6
    }
}

Compression settings explained:

  • encode: Enables compression with specified algorithms
  • minimum_length: Minimum size for compression
  • level: Compression level (1-9)

Configuration Generator

Generated Configuration
# Caddy configuration will appear here

Best Practices

Recommended Practices
  • Static Assets:
    • Use long cache times (1 year) with versioned URLs
    • Add Cache-Control: public for CDN caching
    • Enable compression for text-based assets
  • Dynamic Content:
    • Use shorter cache times
    • Implement cache busting for updates
    • Consider using no-cache for user-specific content
  • API Responses:
    • Use no-store for sensitive data
    • Implement ETag headers for validation
    • Consider using Vary header for different responses