Caddy Static File Server Configuration

Compression

To add gzip encoding support :

:80 {
  root * /srv/www
  file_server
  encode zstd, gzip 
}

Basic Site Configuration Approaches

1. Domain-Based Approach

site.example.com {
    # Configuration here
}

2. Port-Based Approach

:80 {
    @site1 host site.example.com
    handle @site1 {
        # Configuration here
    }
}

Static vs General File Handling

Static Files

General Files

Caching Configuration

Client-Side Caching

header @static {
    Cache-Control "public, max-age=604800, must-revalidate"
}

Server-Side Caching

Complete Configuration Example

:80 {
    # Global compression
    encode zstd gzip

    # Security headers
    header {
        Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; object-src 'none'"
    }

    # Static file handling
    @static {
        file
        path *.css *.js *.jpg *.jpeg *.png *.gif *.ico *.svg *.woff *.woff2
    }
    handle @static {
        header Cache-Control "public, max-age=604800, must-revalidate"
    }

    # Site configurations
    @site1 host site1.example.com
    handle @site1 {
        root * /path/to/site1
    }

    # Global file server
    file_server
}

Best Practices

  1. Header Order

    • Place global headers before handling directives
    • Security headers should be defined early in the configuration
  2. File Serving

    • Use a single global file_server directive when possible
    • Only specify roots in site-specific handlers
  3. Compression

    • Apply compression globally using encode zstd gzip
    • Let Caddy handle compression automatically
  4. Security

    • Always include Content Security Policy (CSP) headers
    • Use appropriate Cache-Control directives
    • Consider additional security headers as needed
  5. Caching Strategy

    • Use client-side caching for static assets
    • Consider server-side caching only if needed
    • Include must-revalidate for better cache control

Common Issues

  1. CSS/JS Not Loading

    • Check CSP headers
    • Verify file permissions
    • Confirm correct file paths
    • Ensure style-src and script-src are properly configured
  2. Caching Issues

    • Verify Cache-Control header syntax
    • Check browser developer tools
    • Clear browser cache during testing
  3. Multiple Site Configuration

    • Use appropriate matching based on hosts
    • Maintain correct root paths
    • Keep shared configurations at the global level

Sources

↑ Back to the top