### Badger Embedded Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Provides examples for configuring Badger as an embedded key-value store for Caddy's cache handler. Covers basic path configuration and advanced Badger options. ```caddy route /badger-path { cache { ttl 15s badger { path /tmp/badger/cache } } respond "Cached with Badger" } route /badger-advanced { cache { ttl 15s badger { configuration { Dir /tmp/badger-data ValueDir /tmp/badger-values ValueLogFileSize 16777216 MemTableSize 4194304 ValueThreshold 524288 SyncWrites true NumVersionsToKeep 1 } } } respond "Advanced Badger config" } ``` -------------------------------- ### Minimal Caddy Cache Configuration Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This Caddyfile configuration demonstrates the most basic setup for enabling the cache module globally and on a specific site. It caches responses for 120 seconds by default. ```caddy { \ cache \ } example.com { cache reverse_proxy your-app:8080 } ``` -------------------------------- ### Configure Olric Cache with Embedded Configuration (Incorrect Example) Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This snippet attempts to configure Olric in embedded mode using a 'configuration' block, but it incorrectly uses NutsDB directives. The Olric provider in embedded mode typically relies on a YAML file specified by 'path', not a direct 'configuration' block with NutsDB options. This example highlights a potential misconfiguration. ```caddyfile olric-configuration.com { cache { nuts { configuration { Dir /tmp/nuts-configuration EntryIdxMode 1 RWMode 0 SegmentSize 1024 NodeNum 42 SyncEnable true StartFileLoadingMode 1 } } } } ``` -------------------------------- ### Redis Distributed Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Shows how to configure Redis as a distributed cache backend for Caddy. Includes examples for basic URL configuration and detailed connection pooling settings. ```caddy { cache { ttl 300s redis { url 127.0.0.1:6379 } } } # Or with detailed configuration route /redis-config { cache { ttl 5s redis { configuration { Addr 127.0.0.1:6379 Username user Password password DB 1 MaxRetries 3 DialTimeout 5s ReadTimeout 5s WriteTimeout 5s PoolSize 100 MinIdleConns 10 MaxIdleConns 50 ConnMaxIdleTime 5s } } } respond "Cached with Redis" } ``` -------------------------------- ### Configure Allowed HTTP Verbs for Caching - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Specify which HTTP methods (e.g., GET, POST, PATCH) are allowed to be cached. This is useful for controlling caching behavior based on the nature of the request. ```caddy { cache { allowed_http_verbs GET POST PATCH ttl 120s } } example.com { cache reverse_proxy backend:8080 } ``` -------------------------------- ### Configure Olric Cache in Embedded Mode with Path Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This configuration demonstrates the Olric cache provider in embedded mode, using a YAML configuration file specified by the 'path' directive. This allows Olric to be run directly within the Caddy process, configured via an external file for complex setups. It's an alternative to direct configuration directives. ```caddyfile olric-path.com { cache { olric { path /path/to/olricd.yml } } } ``` -------------------------------- ### Basic Caddy Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Demonstrates the basic Caddyfile configuration for enabling HTTP caching with default TTL and storage. It shows how to apply the cache directive globally and per-route. ```go // Caddyfile configuration { cache { ttl 120s stale 60s } } example.com { cache reverse_proxy backend:8080 } ``` -------------------------------- ### Global Cache Options Configuration in Caddyfile Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This Caddyfile snippet illustrates the comprehensive global options available for the cache module. It includes settings for logging, API configuration, storage options like Badger and Etcd, cache key customization, CDN integration, and more. ```caddy { \ log { level debug } cache { allowed_http_verbs GET POST PATCH api { basepath /some-basepath prometheus souin { basepath /souin-changed-endpoint-path } } badger { path the_path_to_a_file.json } cache_keys { .*\.css { disable_body disable_host disable_method disable_query headers X-Token Authorization hide } } cache_name Another cdn { api_key XXXX dynamic email darkweak@protonmail.com hostname domain.com network your_network provider fastly strategy soft service_id 123456_id zone_id anywhere_zone } etcd { configuration { # Your etcd configuration here } } key { disable_body disable_host disable_method headers Content-Type Authorization } log_level debug mode bypass nuts { path /path/to/the/storage } olric { url url_to_your_cluster:3320 path the_path_to_a_file.yaml configuration { # Your olric configuration here } } regex { exclude /test2.* } stale 200s ttl 1000s default_cache_control no-store } } :4443 respond "Hello World!" ``` -------------------------------- ### Use Cache Handler as a Caddy Module in Go Applications Source: https://context7.com/caddyserver/cache-handler/llms.txt This Go code shows how to integrate the cache handler as a Caddy module. It includes registering the module, defining a configuration structure, and implementing the ServeHTTP middleware for custom cache handling logic within a Go application. ```go package main import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/cache-handler" ) // Register the module func init() { caddy.RegisterModule(httpcache.SouinCaddyMiddleware{}) } // Configuration structure type CacheConfig struct { TTL string `json:"ttl,omitempty"` Stale string `json:"stale,omitempty"` DefaultCacheControl string `json:"default_cache_control,omitempty"` AllowedHTTPVerbs []string `json:"allowed_http_verbs,omitempty"` LogLevel string `json:"log_level,omitempty"` } // ServeHTTP middleware implementation func (s *httpcache.SouinCaddyMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { return s.SouinBaseHandler.ServeHTTP(w, r, func(w http.ResponseWriter, _ *http.Request) error { return next.ServeHTTP(w, r) }) } ``` -------------------------------- ### Configure Badger Cache with Path Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This Caddyfile configuration snippet demonstrates how to set up the Badger cache provider using a specified directory path. It requires the 'path' directive within the badger configuration block. This is suitable for simple deployments where a file path is sufficient. ```caddyfile badger-path.com { cache { badger { path /tmp/badger/first-match } } } ``` -------------------------------- ### Configure Cache Handler using Caddy's JSON Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt This JSON configuration demonstrates how to set up the cache handler using Caddy's structured JSON format. It defines global cache settings like TTL and headers, and specific route-level cache configurations. ```json { "apps": { "cache": { "headers": [ "Content-Type", "Authorization" ], "log_level": "info", "ttl": "1000s" }, "http": { "servers": { "srv0": { "listen": [":80"], "routes": [ { "match": [ { "path": ["/api/*"] } ], "handle": [ { "handler": "cache", "ttl": "30s" } ] }, { "handle": [ { "handler": "cache" } ] } ] } } } } } ``` -------------------------------- ### Configure Badger Cache with Detailed Configuration Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This snippet shows the Badger cache provider configured with a comprehensive set of options via the 'configuration' directive. It allows fine-tuning of BadgerDB's performance characteristics, such as memory usage, compression, and concurrency. This is useful for advanced optimization. ```caddyfile badger-configuration.com { cache { badger { configuration { # Required value ValueDir # Optional SyncWrites NumVersionsToKeep ReadOnly Compression InMemory MetricsEnabled MemTableSize BaseTableSize BaseLevelSize LevelSizeMultiplier TableSizeMultiplier MaxLevels VLogPercentile ValueThreshold NumMemtables BlockSize BloomFalsePositive BlockCacheSize IndexCacheSize NumLevelZeroTables NumLevelZeroTablesStall ValueLogFileSize ValueLogMaxEntries NumCompactors CompactL0OnClose LmaxCompaction ZSTDCompressionLevel VerifyValueChecksum EncryptionKey EncryptionKeyRotationDuration BypassLockGuard ChecksumVerificationMode DetectConflicts NamespaceOffset } } } } ``` -------------------------------- ### Configure Storage Chain with Fallback - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Define multiple storage providers (e.g., otter, nuts, badger, redis) for caching, with fallback support. Caddy will attempt to use them in the specified order. ```caddy { cache { ttl 300s storers otter nuts badger redis otter { configuration { size 10000 } } nuts { path /tmp/nuts } badger { path /tmp/badger } redis { url 127.0.0.1:6379 } } } ``` -------------------------------- ### Etcd Distributed Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Demonstrates how to configure Etcd as a distributed cache backend for Caddy, suitable for cluster deployments. Includes detailed Etcd client configuration options. ```caddy route /etcd { cache { ttl 5s etcd { configuration { Endpoints etcd1:2379 etcd2:2379 etcd3:2379 AutoSyncInterval 1s DialTimeout 1s DialKeepAliveTime 1s DialKeepAliveTimeout 1s MaxCallSendMsgSize 10000000 MaxCallRecvMsgSize 10000000 Username john Password doe RejectOldCluster false PermitWithoutStream false } } } respond "Hello etcd" } ``` -------------------------------- ### Basic Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Configure HTTP caching with default TTL and storage backend. ```APIDOC ## Basic Cache Configuration ### Description Configure HTTP caching with default TTL and storage backend. ### Method N/A (Caddyfile directive) ### Endpoint N/A (Caddyfile directive) ### Parameters #### Global Configuration (within `cache {}` block) - **ttl** (duration) - Optional - Default TTL for cache entries (e.g., `120s`). - **stale** (duration) - Optional - How long to serve stale cache entries after expiration (e.g., `60s`). #### Per-Site Configuration (within site block) - **cache** - Enables caching for the site with default settings. ### Request Example ```caddy { cache { ttl 120s stale 60s } } example.com { cache reverse_proxy backend:8080 } ``` ### Response #### Success Response (200) N/A (This is a configuration directive, not an API endpoint.) #### Response Example N/A ``` -------------------------------- ### Configure NutsDB Cache with Detailed Configuration Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This configuration sets up the NutsDB cache provider with a comprehensive set of parameters via the 'configuration' directive. It allows control over data directory, indexing modes, read/write modes, segment size, and synchronization. This enables fine-tuning NutsDB for specific storage and performance needs. ```caddyfile nuts-configuration.com { cache { nuts { configuration { Dir /tmp/nuts-configuration EntryIdxMode 1 RWMode 0 SegmentSize 1024 NodeNum 42 SyncEnable true StartFileLoadingMode 1 } } } } ``` -------------------------------- ### Configure Cache Key Generation - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Customize how cache keys are generated by disabling or enabling specific request components like host, method, query parameters, and headers. Supports global and per-pattern configurations. ```caddy { cache { ttl 300s # Global key configuration key { disable_host disable_method headers Authorization Content-Type hash } # Per-pattern key configuration cache_keys { .*\.css { disable_body disable_host disable_method disable_query headers X-Token hide } /api/.* { headers Authorization X-API-Key } } } } route /custom-key { cache { cache_keys { /.+ { headers Authorization } } } respond "Cached with custom key" } ``` -------------------------------- ### Per-Route Caddy Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Illustrates how to configure cache settings on a per-route basis in Caddy, allowing for custom TTL and header-based caching strategies for specific paths. ```caddy @api path /api/* @static path /static/* cache @api { ttl 30s stale 10s } cache @static { ttl 3600s headers Content-Type } ``` -------------------------------- ### Badger Embedded Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Configure Badger as an embedded key-value store for caching. ```APIDOC ## Badger Embedded Cache Configuration ### Description Configure Badger as an embedded key-value store for caching. ### Method N/A (Caddyfile directive) ### Endpoint N/A (Caddyfile directive) ### Parameters #### Badger Configuration (within `cache { badger {} }` block) - **path** (string) - Optional - Path to the directory where BadgerDB data will be stored. - **configuration** (object) - Optional - Advanced BadgerDB configuration options. - **Dir** (string) - Path to the BadgerDB directory. - **ValueDir** (string) - Path to the directory for value log files. - **ValueLogFileSize** (integer) - Size of each value log file in bytes. - **MemTableSize** (integer) - Size of the in-memory table. - **ValueThreshold** (integer) - Threshold for storing values in the value log. - **SyncWrites** (boolean) - Whether to sync writes to disk. - **NumVersionsToKeep** (integer) - Number of versions of a key to keep. ### Request Example ```caddy route /badger-path { cache { ttl 15s badger { path /tmp/badger/cache } } respond "Cached with Badger" } route /badger-advanced { cache { ttl 15s badger { configuration { Dir /tmp/badger-data ValueDir /tmp/badger-values ValueLogFileSize 16777216 MemTableSize 4194304 ValueThreshold 524288 SyncWrites true NumVersionsToKeep 1 } } } respond "Advanced Badger config" } ``` ### Response #### Success Response (200) N/A (This is a configuration directive, not an API endpoint.) #### Response Example N/A ``` -------------------------------- ### Configure CDN Provider Integration for Cache Purging Source: https://context7.com/caddyserver/cache-handler/llms.txt This snippet shows how to configure CDN providers like Fastly and Akamai for cache purging. It specifies API keys, service IDs, and hostnames relevant to each provider. The 'dynamic' option enables dynamic purging, and 'strategy hard' enforces a strict cache invalidation. ```caddy { cache { ttl 300s cdn { provider fastly api_key XXXX service_id 123456_id dynamic strategy hard } } } # Akamai configuration route /akamai { cache { cdn { provider akamai hostname domain.com api_key XXXX email user@example.com } } } ``` -------------------------------- ### Configure Cache Handler Logging Levels Source: https://context7.com/caddyserver/cache-handler/llms.txt This configuration shows how to adjust logging levels for the cache handler. It demonstrates setting a global log level for Caddy and specific log levels for the cache handler, including options for 'debug' and 'info' to control verbosity. ```caddy { log { level debug } cache { log_level debug ttl 300s } } route /verbose { cache { log_level info } respond "Logged at info level" } ``` -------------------------------- ### Enable Cache Management APIs with Prometheus Metrics Source: https://context7.com/caddyserver/cache-handler/llms.txt This configuration enables cache management APIs and Prometheus metrics for monitoring. It sets base paths for the API and metrics endpoints, allowing for external management and observation of the cache's performance. ```caddy { cache { ttl 300s api { basepath /cache-api prometheus { basepath /metrics } souin { basepath /souin } } } } # Access metrics at: http://localhost/cache-api/metrics # Manage cache at: http://localhost/cache-api/souin ``` -------------------------------- ### Etcd Distributed Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Configure Etcd as a distributed cache backend for cluster deployments. ```APIDOC ## Etcd Distributed Cache Configuration ### Description Configure Etcd as a distributed cache backend for cluster deployments. ### Method N/A (Caddyfile directive) ### Endpoint N/A (Caddyfile directive) ### Parameters #### Etcd Configuration (within `cache { etcd {} }` block) - **configuration** (object) - Required - Etcd client configuration. - **Endpoints** (array of strings) - List of Etcd cluster endpoints (e.g., `["etcd1:2379", "etcd2:2379"]`). - **AutoSyncInterval** (duration) - Interval for automatically syncing with the Etcd cluster. - **DialTimeout** (duration) - Timeout for dialing Etcd endpoints. - **DialKeepAliveTime** (duration) - Keep-alive time for Etcd connections. - **DialKeepAliveTimeout** (duration) - Keep-alive timeout for Etcd connections. - **MaxCallSendMsgSize** (integer) - Maximum message size for sending to Etcd. - **MaxCallRecvMsgSize** (integer) - Maximum message size for receiving from Etcd. - **Username** (string) - Username for Etcd authentication. - **Password** (string) - Password for Etcd authentication. - **RejectOldCluster** (boolean) - Whether to reject connections to old cluster versions. - **PermitWithoutStream** (boolean) - Whether to permit connections without streaming enabled. ### Request Example ```caddy route /etcd { cache { ttl 5s etcd { configuration { Endpoints etcd1:2379 etcd2:2379 etcd3:2379 AutoSyncInterval 1s DialTimeout 1s DialKeepAliveTime 1s DialKeepAliveTimeout 1s MaxCallSendMsgSize 10000000 MaxCallRecvMsgSize 10000000 Username john Password doe RejectOldCluster false PermitWithoutStream false } } } respond "Hello etcd" } ``` ### Response #### Success Response (200) N/A (This is a configuration directive, not an API endpoint.) #### Response Example N/A ``` -------------------------------- ### Configure Vary Header Support for Caching - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Enable caching responses based on specific request headers listed in the `Vary` header. This ensures that different header values result in distinct cached entries. ```caddy route /vary { cache { ttl 15s } header Vary "X-Something, Accept-Encoding" respond "Hello {http.request.header.X-Something}" } ``` -------------------------------- ### CDN Management Integration Source: https://github.com/caddyserver/cache-handler/blob/master/README.md Configure Souin to integrate with Content Delivery Networks (CDNs) by specifying the provider, API credentials, and caching strategies. ```APIDOC ## CDN Management ### Description Configure Souin's integration with Content Delivery Networks (CDNs) to manage cache purging and other CDN-specific operations. ### Method N/A (Configuration Directives) ### Endpoint N/A (Configuration Directives) ### Parameters #### CDN Settings - **`cdn`** (object) - Optional - Main configuration block for CDN management. - **`cdn.provider`** (string) - Optional - Specifies the CDN provider (e.g., `akamai`, `fastly`, `souin`). - **`cdn.api_key`** (string) - Optional - The API key used to access the CDN provider. - **`cdn.dynamic`** (boolean) - Optional - Enables dynamic keys returned by the backend application (default: `true`). - **`cdn.email`** (string) - Optional - The API email if required by the CDN provider. - **`cdn.hostname`** (string) - Optional - The hostname of the CDN if required. - **`cdn.network`** (string) - Optional - The network identifier if required by the CDN provider. - **`cdn.strategy`** (string) - Optional - The strategy to use for purging the CDN cache (`hard` or `soft`, default: `soft`). `soft` keeps content as a stale resource. - **`cdn.service_id`** (string) - Optional - The service ID if required by the CDN provider. - **`cdn.zone_id`** (string) - Optional - The zone ID if required by the CDN provider. ### Request Example ```json { "cdn": { "provider": "fastly", "service_id": "123456_id", "api_key": "XXXX", "zone_id": "anywhere_zone", "strategy": "hard" } } ``` ### Response #### Success Response (200) N/A (Configuration applies to Caddy's behavior) #### Response Example N/A ``` -------------------------------- ### Configure Etcd Cache with Configuration Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This Caddyfile configuration uses the Etcd cache provider with detailed settings. It requires the 'configuration' directive and allows specifying Etcd cluster endpoints, connection timeouts, authentication details, and other operational parameters. This is for integrating Caddy with an existing Etcd cluster for distributed caching. ```caddyfile etcd-configuration.com { cache { etcd { configuration { Endpoints etcd1:2379 etcd2:2379 etcd3:2379 AutoSyncInterval 1s DialTimeout 1s DialKeepAliveTime 1s DialKeepAliveTimeout 1s MaxCallSendMsgSize 10000000 MaxCallRecvMsgSize 10000000 Username john Password doe RejectOldCluster false PermitWithoutStream false } } } } ``` -------------------------------- ### Cache Directive Syntax Configuration in Caddyfile Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This Caddyfile configuration showcases the syntax for the cache directive within a specific handle block. It allows for fine-grained control over caching behavior for matched requests, including cache name, key customization, CDN settings, and TTL. ```caddy @match path /path handle @match { cache { cache_name ChangeName cache_keys { (host1|host2).*\.css { disable_body disable_host disable_method disable_query headers X-Token Authorization } } cdn { api_key XXXX dynamic email darkweak@protonmail.com hostname domain.com network your_network provider fastly strategy soft service_id 123456_id zone_id anywhere_zone } key { disable_body disable_host disable_method disable_query headers Content-Type Authorization } log_level debug regex { exclude /test2.* } stale 200s ttl 1000s default_cache_control no-store } } ``` -------------------------------- ### Configure Surrogate Key-Based Cache Invalidation - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Set up surrogate key-based cache invalidation by specifying surrogate keys in headers. Also shows how to disable surrogate keys globally. ```caddy route /surrogate-keys { cache header Surrogate-Key "KEY-{http.request.header.X-Surrogate-Key-Suffix}" header Vary "X-Surrogate-Key-Suffix, Accept-Encoding" respond "Tagged content: {http.request.header.X-Surrogate-Key-Suffix}" } # Disable surrogate keys globally { cache { disable_surrogate_key ttl 300s } } ``` -------------------------------- ### Enable Edge Side Includes (ESI) Tag Processing Source: https://context7.com/caddyserver/cache-handler/llms.txt This configuration enables Edge Side Includes (ESI) tag processing within Caddy. It defines routes that serve HTML content with ESI tags, allowing fragments to be dynamically included from other URLs, including alternate content. ```caddy route /esi { cache header Content-Type "text/html" respond `` } route /esi-include { cache header Content-Type "text/html" respond "

ESI INCLUDED CONTENT

" } route /alt-esi-include { cache header Content-Type "text/html" respond "

ALTERNATE ESI CONTENT

" } ``` -------------------------------- ### NutsDB Embedded Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Illustrates how to set up NutsDB as an embedded key-value cache storage for Caddy. Includes basic path configuration and advanced NutsDB options. ```caddy route /nuts { cache { ttl 15s nuts { path /tmp/nuts-cache } } respond "NutsDB cache" } route /nuts-advanced { cache { ttl 15s nuts { configuration { Dir /tmp/nuts-data EntryIdxMode 1 RWMode 0 SegmentSize 1024 NodeNum 42 SyncEnable true StartFileLoadingMode 1 } } } respond "NutsDB advanced config" } ``` -------------------------------- ### Configure Cache and Backend Timeouts - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Set timeouts for backend requests and cache access. This helps prevent requests from hanging indefinitely and improves resilience. ```caddy { cache { ttl 300s timeout { backend 10s cache 100ms } } } route /backend-timeout { cache { timeout { backend 1s cache 1ms } } reverse_proxy slow-backend:8081 } ``` -------------------------------- ### Configure NutsDB Cache with Path Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This snippet illustrates the NutsDB cache provider configured using a file path. It utilizes the 'path' directive to specify the directory where NutsDB data will be stored. This is a straightforward method for local file-based caching with NutsDB. ```caddyfile nuts-path.com { cache { nuts { path /tmp/nuts-path } } } ``` -------------------------------- ### Cache Compressed Responses with Proper Encoding Headers Source: https://context7.com/caddyserver/cache-handler/llms.txt This snippet configures Caddy to cache compressed responses using gzip. It includes the `encode gzip` directive and sets a `minimum_length` for compression. The cache handler will store the compressed version, and Caddy will serve it with appropriate `Content-Encoding` headers. ```caddy route /gzip { cache { ttl 300s } encode { gzip minimum_length 1024 } header Content-Type "text/plain" respond "Large response body that will be compressed and cached..." } ``` -------------------------------- ### Olric Distributed Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Shows configurations for Olric as a distributed in-memory cache backend in Caddy, covering both client and embedded modes. ```caddy # Client mode route /olric-client { cache { ttl 60s olric { url olric-cluster:3320 } } respond "Olric client mode" } # Embedded mode route /olric-embedded { cache { ttl 60s olric { path /path/to/olricd.yml } } respond "Olric embedded mode" } ``` -------------------------------- ### Configure Olric Cache in Client Mode with URL Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This Caddyfile shows the Olric cache provider configured in client mode, connecting to an Olric cluster via a URL. The 'url' directive is essential for this mode, specifying the address of the Olric server. This is used when Caddy acts as a client to a separate Olric instance. ```caddyfile olric-url.com { cache { olric { url olric:3320 } } } ``` -------------------------------- ### Cache Key Customization Source: https://github.com/caddyserver/cache-handler/blob/master/README.md Configure how cache keys are generated by specifying which parts of the request (body, host, method, query) to include or exclude. You can also add custom headers to be part of the cache key and hide specific keys from the response. ```APIDOC ## Cache Key Configuration ### Description Customize how cache keys are generated by including or excluding specific request components and adding custom headers. ### Method N/A (Configuration Directives) ### Endpoint N/A (Configuration Directives) ### Parameters #### Key Settings - **`cache_keys.{your regexp}.disable_body`** (boolean) - Optional - Disables the body part in the key matching the regexp (e.g., for GraphQL). - **`cache_keys.{your regexp}.disable_host`** (boolean) - Optional - Disables the host part in the key matching the regexp. - **`cache_keys.{your regexp}.disable_method`** (boolean) - Optional - Disables the method part in the key matching the regexp. - **`cache_keys.{your regexp}.disable_query`** (boolean) - Optional - Disables the query string part in the key matching the regexp. - **`cache_keys.{your regexp}.headers`** (string) - Optional - Adds specified headers to the cache key matching the regexp (e.g., `Authorization Content-Type X-Additional-Header`). - **`cache_keys.{your regexp}.hide`** (boolean) - Optional - Prevents the key from being exposed in the `Cache-Status` HTTP response header. ### Request Example ```json { "cache_keys.my_graphql_requests.disable_body": true, "cache_keys.api.headers": "Authorization", "cache_keys.sensitive.hide": true } ``` ### Response #### Success Response (200) N/A (Configuration applies to Caddy's behavior) #### Response Example N/A ``` -------------------------------- ### NutsDB Embedded Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Configure NutsDB as an embedded key-value cache storage. ```APIDOC ## NutsDB Embedded Cache Configuration ### Description Configure NutsDB as an embedded key-value cache storage. ### Method N/A (Caddyfile directive) ### Endpoint N/A (Caddyfile directive) ### Parameters #### NutsDB Configuration (within `cache { nuts {} }` block) - **path** (string) - Optional - Path to the directory where NutsDB data will be stored. - **configuration** (object) - Optional - Advanced NutsDB configuration options. - **Dir** (string) - Path to the NutsDB directory. - **EntryIdxMode** (integer) - Entry index mode (e.g., 1). - **RWMode** (integer) - Read/write mode (e.g., 0). - **SegmentSize** (integer) - Size of data segments. - **NodeNum** (integer) - Number of nodes. - **SyncEnable** (boolean) - Whether to enable data synchronization. - **StartFileLoadingMode** (integer) - Mode for loading files at startup. ### Request Example ```caddy route /nuts { cache { ttl 15s nuts { path /tmp/nuts-cache } } respond "NutsDB cache" } route /nuts-advanced { cache { ttl 15s nuts { configuration { Dir /tmp/nuts-data EntryIdxMode 1 RWMode 0 SegmentSize 1024 NodeNum 42 SyncEnable true StartFileLoadingMode 1 } } } respond "NutsDB advanced config" } ``` ### Response #### Success Response (200) N/A (This is a configuration directive, not an API endpoint.) #### Response Example N/A ``` -------------------------------- ### Redis Distributed Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Configure Redis as a distributed cache backend with connection pooling. ```APIDOC ## Redis Distributed Cache Configuration ### Description Configure Redis as a distributed cache backend with connection pooling. ### Method N/A (Caddyfile directive) ### Endpoint N/A (Caddyfile directive) ### Parameters #### Redis Configuration (within `cache { redis {} }` block) - **url** (string) - Optional - Redis connection URL (e.g., `127.0.0.1:6379`). - **configuration** (object) - Optional - Advanced Redis client configuration. - **Addr** (string) - Address of the Redis server. - **Username** (string) - Username for Redis authentication. - **Password** (string) - Password for Redis authentication. - **DB** (integer) - Database number to use. - **MaxRetries** (integer) - Maximum number of retries for commands. - **DialTimeout** (duration) - Timeout for dialing the Redis server. - **ReadTimeout** (duration) - Timeout for reading from the Redis server. - **WriteTimeout** (duration) - Timeout for writing to the Redis server. - **PoolSize** (integer) - Maximum number of connections in the pool. - **MinIdleConns** (integer) - Minimum number of idle connections. - **MaxIdleConns** (integer) - Maximum number of idle connections. - **ConnMaxIdleTime** (duration) - Maximum time a connection can be idle. ### Request Example ```caddy { cache { ttl 300s redis { url 127.0.0.1:6379 } } } # Detailed configuration example route /redis-config { cache { ttl 5s redis { configuration { Addr 127.0.0.1:6379 Username user Password password DB 1 MaxRetries 3 DialTimeout 5s ReadTimeout 5s WriteTimeout 5s PoolSize 100 MinIdleConns 10 MaxIdleConns 50 ConnMaxIdleTime 5s } } } respond "Cached with Redis" } ``` ### Response #### Success Response (200) N/A (This is a configuration directive, not an API endpoint.) #### Response Example N/A ``` -------------------------------- ### Configure Redis Cache Provider in Caddyfile Source: https://github.com/caddyserver/cache-handler/blob/master/README.md This snippet shows how to configure the Redis cache provider within a Caddyfile. It requires either a redis-url or a redis configuration block, specifying the connection details for the Redis server. ```caddyfile redis-url.com { cache { redis { url 127.0.0.1:6379 } } } ``` -------------------------------- ### Control Caching with Cache-Control Directives - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Utilize upstream `Cache-Control` headers like `s-maxage`, `max-age`, and `must-revalidate` to precisely govern caching durations and validation behavior. ```caddy route /cache-s-maxage { cache header Cache-Control "s-maxage=10" respond "Cached for 10 seconds" } route /cache-maxage { cache header Cache-Control "max-age=5" respond "Cached for 5 seconds" } route /must-revalidate { cache { ttl 5s stale 5s } header Cache-Control "must-revalidate" reverse_proxy backend:8080 } ``` -------------------------------- ### Configure Cache Modes - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Control RFC 7234 compliance for caching using different modes: bypass, bypass_request, bypass_response, and strict. Each mode affects how Cache-Control headers are interpreted. ```caddy # Bypass mode - ignore Cache-Control headers route /bypass { cache { mode bypass ttl 300s } header Cache-Control "no-store" respond "Cached despite no-store" } # Bypass request - ignore request Cache-Control route /bypass_request { cache { mode bypass_request ttl 300s } respond "Ignores request cache headers" } # Bypass response - ignore response Cache-Control route /bypass_response { cache { mode bypass_response ttl 300s } header Cache-Control "no-cache, no-store" respond "Ignores response cache headers" } # Strict mode - full RFC 7234 compliance (default) route /strict { cache { mode strict ttl 300s } respond "Strict RFC compliance" } ``` -------------------------------- ### Configure Regex Exclusion for Caching - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Use regular expressions to exclude specific URL patterns from being cached. This is useful for dynamic content or sensitive paths. ```caddy { cache { ttl 300s regex { exclude /admin/.*|/api/private/.* } } } ``` -------------------------------- ### Olric Distributed Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Configure Olric for distributed in-memory caching with client or embedded mode. ```APIDOC ## Olric Distributed Cache Configuration ### Description Configure Olric for distributed in-memory caching with client or embedded mode. ### Method N/A (Caddyfile directive) ### Endpoint N/A (Caddyfile directive) ### Parameters #### Olric Configuration (within `cache { olric {} }` block) - **url** (string) - Optional - Olric cluster endpoint URL (for client mode). - **path** (string) - Optional - Path to Olric configuration file (for embedded mode). ### Request Example ```caddy # Client mode route /olric-client { cache { ttl 60s olric { url olric-cluster:3320 } } respond "Olric client mode" } # Embedded mode route /olric-embedded { cache { ttl 60s olric { path /path/to/olricd.yml } } respond "Olric embedded mode" } ``` ### Response #### Success Response (200) N/A (This is a configuration directive, not an API endpoint.) #### Response Example N/A ``` -------------------------------- ### Per-Route Cache Configuration Source: https://context7.com/caddyserver/cache-handler/llms.txt Override cache settings for specific routes with custom TTL values. ```APIDOC ## Per-Route Cache Configuration ### Description Override cache settings for specific routes with custom TTL values. ### Method N/A (Caddyfile directive) ### Endpoint N/A (Caddyfile directive) ### Parameters #### Route Configuration (within `cache @matcher {}` block) - **ttl** (duration) - Optional - TTL for cache entries for this specific route. - **stale** (duration) - Optional - How long to serve stale cache entries for this route. - **headers** (string) - Optional - Cache based on specified request headers (e.g., `Content-Type`). ### Request Example ```caddy @api path /api/* @static path /static/* cache @api { ttl 30s stale 10s } cache @static { ttl 3600s headers Content-Type } ``` ### Response #### Success Response (200) N/A (This is a configuration directive, not an API endpoint.) #### Response Example N/A ``` -------------------------------- ### Set Default Cache-Control Header - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Define a default Cache-Control header value to be used when the upstream response does not provide one. This ensures consistent caching behavior. ```caddy { cache { ttl 300s default_cache_control "public, max-age=3600" } } route /no-cache-control { cache { default_cache_control "no-store" } respond "Response without cache control" } ``` -------------------------------- ### Limit Max Cacheable Body Size - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Configure the maximum response body size in bytes that can be cached. This prevents excessively large responses from consuming too much memory. ```caddy { cache { ttl 300s max_cacheable_body_bytes 1048576 # 1MB } } example.com { cache reverse_proxy backend:8080 } ``` -------------------------------- ### Allow Caching of Additional Status Codes Source: https://context7.com/caddyserver/cache-handler/llms.txt This snippet configures the cache handler to cache responses with additional HTTP status codes beyond the defaults (e.g., 200, 301, 302). It allows specifying codes like 404, 500, or 503 to be cached. ```caddy { cache { ttl 300s allowed_additional_status_codes 404 500 503 } } example.com { cache reverse_proxy backend:8080 } ``` -------------------------------- ### Configure Cache Name in Cache-Status Header - Caddyfile Source: https://context7.com/caddyserver/cache-handler/llms.txt Override the cache name displayed in the `Cache-Status` response header. This allows for custom identification of cache origins. ```caddy route /custom-name { cache { cache_name "MyCustomCache" ttl 300s } respond "Custom cache name" } ``` -------------------------------- ### Disable Request Coalescing for Concurrent Identical Requests Source: https://context7.com/caddyserver/cache-handler/llms.txt This configuration disables request coalescing, a feature where concurrent identical requests are merged into a single upstream request. Disabling this ensures each request is handled independently, which can be useful in specific scenarios. ```caddy { cache { ttl 300s disable_coalescing } } example.com { cache reverse_proxy backend:8080 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.