Files
RustProxy/docs/VCL_TRAFFIC_COOKBOOK.md
T
2026-11-20 23:14:19 +01:00

43 KiB

VCL cookbook: concrete use cases and HTTP traffic scenarios

Target: RustProxy 0.39.2 with the Docker Cache/Traffic and CDN cookie patch. This guide documents the actual importer (src/cache/vcl.rs), validated cache-rule actions (src/cache/rules.rs), and shared-cache admission documented in Cache. It is not a full Varnish implementation or a promise of exact Varnish semantics.

Read together with VCL compatibility and the supported/unsupported capability matrix. The examples are separate policies, not one file that should be imported wholesale. Copy one recipe into the correct Vhost scope, then reconcile it with existing global/local rules; never paste contradictory return(pass) policies together without reviewing rule order.

A. How to use the recipes

  1. Pick a reverse-proxy HTTP Vhost (ordinary Vhost or Docker vhost). Open its Cache rules editor. For site-wide rules use Settings → Cache → Rules, but prefer a local scope for policies about one application.
  2. Enable the global cache and, where intended, the effective per-Vhost cache policy. Check fallback TTL, Varnish-compatible vs strict RFC mode, static-cookie settings, origin response headers and maximum object size. A VCL return(hash) cannot enable a disabled cache.
  3. Import the VCL file in the VCL import dialog. RustProxy translates it to graphical rules. It does not execute a VCL interpreter. Review every generated rule and warning. The importer pauses on warnings; Add partial import (reviewed) is a separate explicit step, and the configuration still needs to be saved.
  4. Use Test a request with method, URL, request headers and simulated backend status/headers; confirm which rule matched and whether a terminal return(pass) was produced. Test both global and local rule precedence. A rule preview is not a live cache HIT test.
  5. Run two real identical GET requests through the proxy. Inspect Cache-Status (RFC 9211), optionally X-Cache/X-Cache-Reason, and the delivered Vary/Cache-Control. Warm a disposable test URL; remove cached objects after changing privacy rules.

Terminology in this guide

Label Meaning
PASS / BYPASS Request uses the backend without shared-cache lookup (or fails normal eligibility checks). A response-stage no-store rule can also prevent a MISS from being stored.
MISS Eligible lookup found no reusable fresh object; origin response is fetched. A MISS does not prove that the response was stored.
HIT An eligible subsequent request uses a fresh matching object, if admission, freshness, storage, and Vary conditions all succeeded.
STALE / REVALIDATED RustProxy's independent grace/stale/conditional machinery may respond without a fresh HIT. Availability and labeling depend on configuration.
Origin contract Conditions the application must guarantee (public identical body/headers, required Vary, validators, no session dependence). VCL does not verify that promise.

Always preserve: authentication and authorization, session boundaries, private/no-store responses, Set-Cookie, client request cache-control and true representation dimensions. If a backend decides which user sees which data, use PASS instead of trying to cache it by Cookie or an untrusted synthetic header.

B. Choose an appropriate policy

Traffic/application Recommended recipe or native setting What it can do What it does not do
CMS articles or a public catalog Public catalog Cache genuinely shared 200 GETs, set TTL/grace Force storage of private, Set-Cookie or 404
Public JSON endpoint for prices/stock Public JSON API Short-lived shared cache Cache credentialed/private API responses
Admin, login, checkout, user dashboard Private routes Bypass shared cache Replace ACL, OIDC, Basic Auth, app permissions
Cookies set broadly by a parent domain Selective parent cookie removal Remove only verified names or trailing-* prefixes, leaving application sessions intact Infer which Domain set them; safely delete an overlapping session cookie name
Cloudflare/Akamai technical cookies CDN cookie allowlist Strip an entire CDN-only Cookie header; separate from parent cookie rule Treat unknown or session cookies as CDN cookies
Public CSS, JS, fonts, images Static assets + native static settings Strip request Cookie if proven safe; optional conditional Vary: Cookie treatment Override any other arbitrary Vary dimension
Multilingual catalog Language variants Preserve origin Vary: Accept-Language and separate variants Automatically translate or change language
Low-cardinality public A/B content A/B variants Add internal header dimension via vcl_hash Write Vary for downstream caches
Server-sent events, webhook traffic, transient errors No-store PASS streaming paths and prevent storage Retry origins, stream hooks, generate synthetic errors
Remove internal diagnostics from the response Header hygiene Change permitted request/delivery headers Modify body, protected headers or cache admission at delivery
Remove tracking parameters from cache identity Query rewrite or graphical Strip query Drop approved params after URL normalization Import arbitrary regsub or preserve regex URL semantics exactly
Origin sets irrelevant Set-Cookie on public SVG Advanced public cookie cleanup Remove it before storage Prove it was not needed for identity/session
CORS responses differentiated by Origin Origin's Vary: Origin Keep origins separate Safely collapse all origins into one cached response
Cache error pages/redirects (404, 301, 302) Not supported No cache storage in 0.39.2 Invent negative/redirect-cache TTL via VCL
IP ranges, backend routing, purge, TLS security Native ACL/Vhost/Cache API settings Dedicated supported configuration Import ACL/director/return(purge) as executable VCL

C. Copy-and-import VCL recipes

All full examples below use only source syntax understood by the RustProxy importer, except recipe 10, whose restricted conversion deliberately emits a warning. The advanced Set-Cookie example is syntactically supported but dangerous without a verified public origin contract.

1. Exclude private routes and unsafe methods

Goal: Keep administration, accounts, cart, checkout, webhooks, cookies and credentials away from shared cache.

Expected traffic: POST /webhook and GET /account/orders → PASS; GET /catalog with a session Cookie → PASS.

Prerequisites: Apply to relevant HTTP reverse-proxy Vhosts; configure app authentication separately.

Caveat: There is no final return(hash); other eligible routes retain normal RustProxy policy and any other saved rules.

Source: examples/vcl/private-routes-bypass.vcl.

// Defensive exclusions for an existing HTTP reverse-proxy vhost.
// Does not opt in to caching for other routes.
sub vcl_recv {
    if (req.method != "GET" && req.method != "HEAD") {
        return(pass);
    }
    if (req.url ~ "^/(admin|api/private|account|auth|login|logout|checkout|cart|dashboard|webhook)(/|[?]|$)") {
        return(pass);
    }
    if (req.http.Authorization) {
        return(pass);
    }
    if (req.http.Cookie) {
        return(pass);
    }
}

2. Public catalog with explicit short TTL

Goal: Allow only anonymous GET/HEAD for /catalog, with 120-second origin-response freshness and 20-second grace.

Expected traffic: First eligible GET is typically MISS; a repeated fresh identical GET may be HIT. POST /catalog and GET /catalog with a Cookie → PASS.

Prerequisites: The origin returns an actually public representation with Cache-Control: public, max-age=120, HTTP 200, no Set-Cookie and correct Vary.

Caveat: The TTL rule may override a shorter origin TTL. Avoid deploying against pages with fluctuating stock, sessions, authorization or incorrectly marked public content.

Source: examples/vcl/public-catalog.vcl.

// Cache only demonstrably public catalog pages. The origin must supply
// Cache-Control: public, max-age=120 and must not vary by user/session.
sub vcl_recv {
    if (req.method != "GET" && req.method != "HEAD") {
        return(pass);
    }
    if (req.http.Authorization || req.http.Cookie) {
        return(pass);
    }
    if (req.url ~ "^/catalog(/|[?]|$)") {
        return(hash);
    }
    return(pass);
}

sub vcl_backend_response {
    if (bereq.url ~ "^/catalog(/|[?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") {
        set beresp.ttl = 120s;
        set beresp.grace = 20s;
    }
}

3. Public GET JSON API

Goal: Cache a controlled, anonymous JSON API for 15 seconds, with 5-second grace.

Expected traffic: GET /api/public/list can MISS→HIT; GET /api/private/me, POST /api/public/list or a request with Authorization bypasses.

Prerequisites: Origin returns JSON, 200 and explicit Cache-Control: public, with no session dependence; all important Vary fields remain intact.

Caveat: A response such as private, no-store, Set-Cookie or invalid Vary remains ineligible. Do not treat public API as all API endpoints.

Source: examples/vcl/public-json-api.vcl.

// GET-only shared caching for /api/public. Other API routes bypass.
// The origin must mark genuinely public JSON responses as such.
sub vcl_recv {
    if (req.method != "GET" && req.method != "HEAD") {
        return(pass);
    }
    if (req.http.Authorization || req.http.Cookie) {
        return(pass);
    }
    if (req.url ~ "^/api/public(/|[?]|$)") {
        return(hash);
    }
    return(pass);
}

sub vcl_backend_response {
    if (bereq.url ~ "^/api/public(/|[?]|$)" && beresp.status == 200 && beresp.http.Content-Type ~ "^application/json" && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") {
        set beresp.ttl = 15s;
        set beresp.grace = 5s;
    }
}

4. CDN technical cookies without dropping sessions

Goal: Ignore only known technical Cloudflare/Akamai cookies while keeping real sessions out of shared cache.

Expected traffic: Cookie: __cf_bm=a; _cfuvid=b → remove Cookie, eligible for lookup; Cookie: __cf_bm=a; session=s → PASS.

Prerequisites: Review the allowlisted names with your CDN provider and origin. Verify the origin does not need these cookie values for bot/challenge flow.

Caveat: Whole-header anchored matching is intentional. Do not replace it with an unanchored test for __cf_bm. Do not add load-balancer affinity, challenge, or application cookies automatically.

Source: examples/vcl/cdn-technical-cookies.vcl.

// Optional template: only shared/public content independent of these cookies.
// Cloudflare: __cf_bm, cf_clearance, _cfuvid, __cfruid, __cfseq
// Akamai: _abck, ak_bmsc, bm_sz, bm_sv
// Security cookies can be needed for bot challenges; review before enabling.
sub vcl_recv {
    if (req.method != "GET" && req.method != "HEAD") {
        return(pass);
    }
    if (req.url ~ "^/(admin|api|auth|login|logout|panel|konto|dashboard)(/|[?]|$)") {
        return(pass);
    }
    if (req.http.Authorization) {
        return(pass);
    }
    // Match the complete Cookie header, not one cookie within it.
    if (req.http.Cookie ~ "^(?:__cf_bm|cf_clearance|_cfuvid|__cfruid|__cfseq|_abck|ak_bmsc|bm_sz|bm_sv)=[^;]*(?:;[ \t]*(?:__cf_bm|cf_clearance|_cfuvid|__cfruid|__cfseq|_abck|ak_bmsc|bm_sz|bm_sv)=[^;]*)*$") {
        unset req.http.Cookie;
    }
    // Remaining cookies: Cookie/session guard. RustProxy extension
    // return(cookie_pass) bypasses pages like return(pass) but lets public
    // static assets use the cache when "Ignore request cookies for static
    // files" is on. In stock Varnish use return(pass) here.
    if (req.http.Cookie) {
        return(cookie_pass);
    }
    return(hash);
}

The final guard uses return(cookie_pass): logged-in pages remain BYPASS (cache_rule_cookie), while public CSS/JS/images/fonts can be shared under the static cookie policy. Use return(pass) there to keep the 0.39.1 behavior. See decision precedence.

Goal: Remove all Cookie headers only from independently verified public /assets images/fonts/scripts/styles.

Expected traffic: GET /assets/site.css with Cookie may use a shared key; other paths remain subject to their original cache policy.

Prerequisites: Every byte and relevant response header is the same for guests and logged-in users; origin produces public 200 and valid freshness.

Caveat: VCL does not implement an Ignore Vary: Cookie instruction. Use Static & diagnostics options; these have additional explicit public/freshness/no-Set-Cookie/privacy checks. A session-aware image must not use this recipe.

Without stripping cookies: if your session guards use return(cookie_pass) (or the session templates), you do not need this recipe for logged-in users: with Ignore request cookies for static files on, public static assets reach the cache while the Cookie is still forwarded, and storage requires an explicitly public backend reply (shared-static guard).

Source: examples/vcl/static-assets-public.vcl.

// Optional: remove ALL request cookies for public, identity-independent
// assets under /assets. Origin must never use a session for these assets.
// Vary: Cookie removal is NOT accomplished by this VCL. Configure the
// native "Ignore Vary: Cookie for public static assets" setting separately.
sub vcl_recv {
    if (req.method != "GET" && req.method != "HEAD") {
        return(pass);
    }
    if (req.url ~ "^/assets/.*[.](css|js|png|jpg|jpeg|svg|woff2)([?]|$)") {
        if (req.http.Authorization) {
            return(pass);
        }
        unset req.http.Cookie;
        return(hash);
    }
}

6. Language-specific representations

Goal: Preserve the origin-defined language dimension rather than flattening it with a header rewrite.

Expected traffic: Accept-Language: pl and Accept-Language: en are distinct variants if the origin sends Vary: Accept-Language.

Prerequisites: The backend really changes representations by language and sends Vary: Accept-Language plus any other dimensions (e.g. Accept-Encoding).

Caveat: Do not set beresp.http.Vary = "Accept-Language" if the origin also varies by compression, Origin, device or another header.

Source: examples/vcl/language-catalog.vcl.

// Origin responsibility: return Vary: Accept-Language (plus any other real
// dimensions such as Accept-Encoding), public freshness and no Set-Cookie.
// Do not replace the origin Vary list with a single dimension.
sub vcl_recv {
    if (req.method != "GET" && req.method != "HEAD") {
        return(pass);
    }
    if (req.http.Authorization || req.http.Cookie) {
        return(pass);
    }
    if (req.url ~ "^/translations(/|[?]|$)") {
        return(hash);
    }
    return(pass);
}

sub vcl_backend_response {
    if (bereq.url ~ "^/translations(/|[?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") {
        set beresp.ttl = 60s;
    }
}

7. Low-cardinality public A/B variants

Goal: Demonstrate vcl_hash with one explicit request-header value for public A/B experiment content.

Expected traffic: X-Experiment: A and X-Experiment: B should partition the internal key; any other value bypasses.

Prerequisites: Clients send the header themselves (also to downstream caches); the origin returns Vary: X-Experiment and does not personalize by user.

Caveat: hash_data does not send Vary to clients; missing Vary can leak a variant through another cache. Keep a strict finite value list to avoid unbounded cardinality.

Source: examples/vcl/experiment-variants.vcl.

// Controlled, PUBLIC A/B variants: client sends X-Experiment: A or B.
// Origin must also return Vary: X-Experiment, preserve other Vary fields,
// and never associate this header with credentials or private data.
sub vcl_recv {
    if (req.method != "GET" && req.method != "HEAD") {
        return(pass);
    }
    if (req.http.Authorization || req.http.Cookie) {
        return(pass);
    }
    if (req.url ~ "^/experiment(/|[?]|$)") {
        if (req.http.X-Experiment ~ "^(A|B)$") {
            return(hash);
        }
        return(pass);
    }
    return(pass);
}

sub vcl_hash {
    hash_data(req.http.X-Experiment);
}

8. Streaming, webhooks and origin errors

Goal: Avoid caching event streams/webhooks and mark SSE/error responses as uncacheable in the response stage.

Expected traffic: GET /events → PASS; an unrelated response with Content-Type: text/event-stream → NoStore; status 5xx → NoStore.

Prerequisites: Use native proxy/WebSocket/stream and backend retry configuration for those separate operations.

Caveat: This is not a Varnish vcl_backend_error, retry, pipe or stale-if-error implementation. 500 was never eligible for 0.39.2 shared storage anyway.

Source: examples/vcl/stream-and-errors-no-store.vcl.

// Defense in depth for streaming and transient backend responses.
// Does not implement retries, synthetic error handling or stale-if-error.
sub vcl_recv {
    if (req.url ~ "^/(events|stream|webhook)(/|[?]|$)") {
        return(pass);
    }
}

sub vcl_backend_response {
    if (beresp.http.Content-Type ~ "^text/event-stream") {
        set beresp.uncacheable = true;
        return(deliver);
    }
    if (beresp.status >= 500) {
        set beresp.uncacheable = true;
    }
}

9. Safe request and delivery header edits

Goal: Remove a non-essential request header, set a constant origin-visible marker, remove an internal response header and tag delivery.

Expected traffic: GET /catalog forwards X-Edge-Policy: catalog-v1; a downstream response no longer exposes X-Debug.

Prerequisites: Changes only use permitted header names. Test both Cache HIT and MISS and the origin request.

Caveat: Deliver-stage edits happen after cache selection; they cannot rescue an ineligible response or safely delete Vary for all downstream caches.

Source: examples/vcl/headers-and-diagnostics.vcl.

// Request header sanitation (safe, ordinary representation headers only).
// Deliver mutations do not change the object stored in cache.
sub vcl_recv {
    if (req.url ~ "^/catalog(/|[?]|$)") {
        unset req.http.X-Marketing-Source;
        set req.http.X-Edge-Policy = "catalog-v1";
    }
}

sub vcl_deliver {
    if (req.url ~ "^/catalog(/|[?]|$)") {
        unset resp.http.X-Debug;
        set resp.http.X-Edge-Policy = "catalog-v1";
    }
}

10. Tracking-query normalization (restricted)

Goal: Normalize a small allowlist of proven non-semantic tracking parameters on /landing.

Expected traffic: GET /landing?utm_source=ad can map to a query-stripped cache target after rule conversion.

Prerequisites: The application guarantees these parameters never affect body, localization, cookies or redirects; inspect the exact generated Strip query rule.

Caveat: An import warning is expected. RustProxy converts the recognized regsuball to a native query action with potentially different separators/empty-value behavior. Review before Add partial import (reviewed). Prefer the graphical action for repeatable configuration.

Source: examples/vcl/tracking-query-restricted.vcl.

// Demonstrates the ONLY recognized req.url regsuball form.
// Import WILL WARN: converted to native strip_query with potentially
// different URL separator/empty-value normalization. Review and accept
// partial import only if the original URL parameters have no origin impact.
sub vcl_recv {
    if (req.url ~ "^/landing([?]|$)") {
        set req.url = regsuball(req.url, "([?&])(utm_source|utm_medium|gclid)=[^&]*", "\1");
    }
}

Goal: Demonstrate the dedicated backend unset beresp.http.Set-Cookie escape hatch for one verified public SVG.

Expected traffic: GET /public/banner.svg may become storable if that was its only storage barrier and all other checks permit it.

Prerequisites: You have independently verified that the exact URL, body and response headers are identical for every visitor and that removing the cookie will not affect session, security or challenge behavior.

Caveat: Never apply globally. Removing the origin cookie and thereby enabling public storage can disclose personalized content. A rule that adds TTL does not bypass other privacy barriers.

Source: examples/vcl/advanced-set-cookie-removal.vcl.

// ADVANCED / HIGH RISK. Only for a verified identical public representation.
// Removes Set-Cookie before storage and before forwarding the origin response.
// NEVER apply to login, accounts, cart, personalized JSON or CSRF flows.
sub vcl_backend_response {
    if (bereq.url ~ "^/public/banner[.]svg([?]|$)" && beresp.status == 200 && beresp.http.Cache-Control ~ "(^|,) *public(,|$)") {
        unset beresp.http.Set-Cookie;
        set beresp.ttl = 1h;
    }
}

12. Parent-domain cookies: remove selected names (opt-in)

Goal: A subdomain receives an unrelated, verified cookie set by a parent domain. Remove only this cookie's name, keeping any session/CSRF/authentication cookies for later BYPASS rules. The HTTP Cookie request header does not identify the issuing Domain. The recommended long-term fix is a host-only Set-Cookie at the issuing app.

Expected traffic: GET /catalog with parent_marketing=1; app_session=abc → remove parent_marketing, preserve app_session, and then the separate CDN remaining cookies rule causes BYPASS. With only parent_marketing=1, RustProxy may cache eligible anonymous content. With parent_marketing=1; __cf_bm=2, the parent rule removes the first and the separate CDN rule removes the second; this allows normal cache lookup. POST, protected paths and Authorization are unaffected.

Prerequisites: On the Vhost, add Vhost: remove selected parent-domain cookies, replace REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME with the verified cookie names or single trailing-* prefixes in Remove selected cookies, review sensitive paths, then enable. Keep the CDN template as its own group of rules, with this new rule above CDN: remove ONLY technical cookies and CDN: bypass remaining cookies. Do not enable a previous ignore ALL inherited cookies rule: it could strip login sessions and force cache lookup. Removing that old rule from existing saved configurations is manual.

Caveat: A cookie name or prefix may be shared by both the parent and the application; if so, do not strip it by name. This is a RustProxy-specific VCL extension rather than standard Varnish VCL. Origin privacy guards, Set-Cookie, and Vary remain active. See Cache.

Source: examples/vcl/public-vhost-remove-parent-cookies.vcl. For a parent Drupal 6 site with dynamic SESS<hash> names and a separate local session cookie, use the Drupal 6 example: it removes SESS*/SSESS* while explicitly bypassing on session. This example requires the prefix-selector-enabled 0.39.1 binary, not an earlier unpatched build. The CDN policy remains separate.

// Opt-in Vhost-only rule, SEPARATE from the CDN technical-cookie template.
// RustProxy VCL extension: remove_req_cookies() is NOT standard Varnish VCL.
// Replace REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME with exact, verified names
// that this Vhost NEVER uses for login, user state, language, cart, etc.
// Cookie headers do NOT reveal Domain; a name may also belong to this Vhost.
// Never list a session cookie that could be valid for this Vhost.
//
// Install ABOVE "CDN: remove ONLY technical cookies" and
// "CDN: bypass remaining cookies", which must stay as separate rules.
// DO NOT use the old strip-all inherited-cookie rule in parallel.
// This rule has no return(hash): remaining cookies and sessions still pass
// through the CDN/normal cache safety checks.
sub vcl_recv {
    if ((req.method == "GET" || req.method == "HEAD") &&
        req.http.Cookie &&
        !req.http.Authorization &&
        req.url !~ "^/(admin|api|auth|login|logout|account|profile|user|settings|dashboard|cart|checkout|panel|konto|wp-admin|wp-login[.]php)(/|[?]|$)") {
        remove_req_cookies("REPLACE_WITH_VERIFIED_PARENT_COOKIE_NAME");
    }
}

D. Real HTTP traffic: what is handled and what is not

The outcomes below describe decision paths, not a guaranteed X-Cache label: proxy route exclusions, access checks, configuration, origin responses, object sizes, validators, time, and storage limits still apply. The word eligible means the request may look up or populate cache if all other conditions succeed.

D1. Requests, cookies and authorization

Incoming request Example policy Decision Important detail
GET /catalog/item/1 (anonymous) Public catalog Eligible lookup First fetch usually MISS; second may HIT.
HEAD /catalog/item/1 Public catalog Eligible method Verify real HEAD behavior rather than assuming it fills the same object as GET.
POST /catalog/item/1 Public catalog PASS VCL does not override unsafe-method restriction.
PUT /api/public/item/1 Public API PASS Mutations do not become cacheable.
GET /account/orders Private routes PASS Authentication and authorization are enforced outside VCL.
GET /api/public/list without credentials Public API Eligible lookup Only public JSON 200 has the example 15-second TTL.
GET /api/private/me Public API PASS Path excluded even without Cookie.
GET /catalog, Authorization: Bearer ... Catalog PASS Credentialed requests are excluded by code and cache safety checks.
GET /catalog, Cookie: session=abc Catalog/CDN PASS No session cookie stripping.
GET /catalog, Cookie: __cf_bm=a CDN cookie allowlist Strip Cookie; eligible Origin receives no Cookie; confirm CDN challenge behavior.
Cookie: __cf_bm=a; cf_clearance=b CDN cookie allowlist Strip whole Cookie header Only exact allowlisted cookie names pass.
Cookie: __cf_bm=a; session=b CDN cookie allowlist PASS Even one non-allowlisted name prevents removal.
Two physical Cookie fields, one technical and one session CDN cookie allowlist PASS Patched matcher examines combined cookie values.
GET /catalog, parent_marketing=a (listed) Parent-name template Remove only listed cookie; eligible The operator must verify the name is not used for app sessions.
parent_marketing=a; __cf_bm=b Parent-name + separate CDN templates Both removed in order; eligible Keep the parent rule before the CDN remaining-cookie bypass.
parent_marketing=a; app_session=b Parent-name + separate CDN templates Preserve app_session; BYPASS Never force lookup for remaining unknown/session cookies.
GET /account, parent-domain Cookie Parent-name template Ordinary bypass/auth rules Protected-path guard leaves Cookie untouched.
GET /catalog, Cookie plus Authorization Parent-name template Native auth/bypass The template does not remove Cookie with Authorization.
GET /assets/site.css, arbitrary Cookie Public static Strip Cookie if verified safe Separate native Vary: Cookie setting has additional conditions.
GET /assets/user-avatar.png, Cookie Do not use static bypass PASS recommended Do not remove session personalization merely due to extension.
GET /experiment, X-Experiment: A A/B variants Eligible A partition Origin must emit downstream Vary: X-Experiment.
GET /experiment, X-Experiment: C A/B variants PASS Unrecognized dimension value intentionally rejected.
POST /webhook Private / stream PASS Rules do not replace request authentication/signature verification.
GET /events, SSE Stream no-store PASS No VCL body streaming/rewrite support.

D2. Origin response and Vary

Backend sends RustProxy 0.39.2 consequence Safety check
200, public/fresh, no Set-Cookie, valid Vary Potential shared-store candidate Response must really be identical for all users.
200, Cache-Control: private Not storable without dangerous explicit rewrite Never rewrite private content to public.
200, Cache-Control: no-store Not storable without dangerous explicit rewrite Do not use header removal to bypass origin policy.
200, Set-Cookie: session=... Not storable normally Dedicated Set-Cookie removal is high risk.
200, Vary: Accept-Encoding Distinct encoding variants Do not unset Vary to increase HIT rate.
200, Vary: Accept-Language, Accept-Encoding Both dimensions preserved An overwrite with only language loses encoding correctness.
200, Vary: Origin Different CORS-Origin variants Do not collapse different allowed origins.
200, Vary: Cookie on genuinely public static Native exception may remove Cookie member Requires configured extension, public positive freshness, no privacy blockers.
200, Vary: Cookie on personalized JSON Preserve or bypass No universal Ignore Vary switch.
200, Vary: * No reusable cached variant Rewrite at application if appropriate; do not force-drop.
200, malformed Vary No reusable cached variant Fix origin response.
200, no-cache and validator Conditional behavior depends on compatibility/fallback Do not assume TTL or forced HIT.
200, no-cache without validator Compatibility fallback may differ from strict mode See Cache mode; verify selected global/per-Vhost settings.
200, Content-Type: text/event-stream NoStore if SSE recipe applies No synthetic stream buffering in VCL.
200, Cache-Control: public, max-age=0 Not fresh solely because public Short-TTL overrides are a deliberate independent administrative decision.
301 / 302 redirect Not storable TTL recipe cannot enable redirect caching.
404 / 410 missing asset Not storable Negative caching not implemented.
500 / 502 / 503 error Not storable Independently configured stale-if-error may use an earlier stored object.
304 response to revalidation Native conditional revalidation Not a programmable vcl_hit / vcl_miss callback.

D3. Deployment, Docker, and other edge conditions

Situation Suggested handling Boundary
Docker container restarts and returns Keep saved per-vhost rules and verify discovered routing after recovery VCL does not start/recreate containers.
Docker container disappears Native health/routing logic; observe possible 503 or eligible stale-if-error vcl_backend_error and VCL retry are unsupported.
Same path on two unrelated domains Per-vhost configuration and normalized Host isolation No cross-vhost shared object or hash_data(Host) requirement.
Cache for only some Docker services Apply rule to the selected Docker vhost or scoped global rules Do not paste one global return(hash) for all apps.
Static file served by the built-in Web Server or PHP Use those components' native settings VCL rule importer is for HTTP reverse-proxy Vhosts.
Source checks for Authorization or TLS client identity Native auth, ACL and transport security These cannot be rewritten in cache VCL.
Range, If-*, request Cache-Control: no-store Native conditional/range/privacy logic Request-rule header mutations cannot override protected headers.
IP/CIDR based cache eligibility Graphical cache-rule client_ip condition or native security ACL client.ip ~ my_acl is not importable.
Tracking params (utm_*, gclid) Graphical Strip query params with an explicit allowlist VCL regsuball is limited and emits a warning.
Debug counters and Cache/Traffic lists Native Cache/Traffic UI and HTTP cache diagnostics VCL has no log writing, metrics API or custom VMOD.

E. Vary decisions: prefer correctness over HIT ratio

  1. Keep origin Vary unless you can prove it is wrong. RustProxy compares retained dimensions, including Accept-Language, Accept-Encoding, Origin, custom headers and Cookie. It normalizes selected list-valued headers but does not generally discard dimensions.
  2. If the origin emits an unnecessary Vary: Cookie for truly public .css/.png/.woff2 files, first try fixing the origin. Otherwise use the narrow native static-asset option (configured extensions + public freshness + no Set-Cookie/privacy); do not use unset beresp.http.Vary.
  3. When a service responds differently by language, compression, device, origin or experiment, retain every actual dimension. set beresp.http.Vary = "Accept-Language" overwrites the whole field; set resp.http.Vary changes only delivery and can mislead downstream caches.
  4. hash_data(req.http.X-Experiment) is internal to RustProxy. The backend still must send Vary: X-Experiment to downstream caches, and clients must actually supply the header to those caches. A header known only to RustProxy cannot safely stand in for a public Vary contract.
  5. Never apply a general Ignore Vary switch or remove Vary: Cookie for account/avatar, session-protected files, locale-by-Cookie or CORS-by-Origin variants.

Example: correctly declared language and encoding variants

GET /translations/home HTTP/1.1
Host: public.example.test
Accept-Language: pl
Accept-Encoding: gzip

HTTP/1.1 200 OK
Cache-Control: public, max-age=60
Vary: Accept-Language, Accept-Encoding
Content-Type: text/html; charset=utf-8

A second request with identical relevant headers may HIT after a successful fill; changing language or encoding must select a different object or fetch it from the origin. If the origin also varies by Origin, the response must include that member too.

F. Inspect behavior with curl (staging environment)

Run against your own test site through the configured TLS listener. The hostname, paths and proxy must be replaced with actual test values. These commands use GET (-o /dev/null -D -) so the result does not depend on the HEAD method's implementation. Enable RustProxy cache diagnostics if you want X-Cache and reason fields; otherwise inspect Cache-Status and response headers.

BASE='https://public.example.test'
# Warm a public resource: watch the first response and the repeated one.
curl -sS -o /dev/null -D - "$BASE/catalog/item/1"
curl -sS -o /dev/null -D - "$BASE/catalog/item/1"

# Login/session and credential-bearing requests must not be served from shared cache.
curl -sS -o /dev/null -D - -H 'Cookie: session=test' "$BASE/catalog/item/1"
curl -sS -o /dev/null -D - -H 'Authorization: Bearer test' "$BASE/catalog/item/1"

# Optional public-Vhost template (after explicitly enabling and reviewing paths):
# browser-equivalent Cookie is removed for genuinely public pages.
curl -sS -o /dev/null -D - -H 'Cookie: parent_session=abc' "$BASE/catalog/item/1"
curl -sS -o /dev/null -D - -H 'Cookie: parent_session=abc' "$BASE/catalog/item/1"

# Technical-only cookies vs mixed cookies: inspect origin logs as well.
curl -sS -o /dev/null -D - -H 'Cookie: __cf_bm=test' "$BASE/catalog/item/1"
curl -sS -o /dev/null -D - -H 'Cookie: __cf_bm=test; session=test' "$BASE/catalog/item/1"

# Private path and non-GET should be bypassed.
curl -sS -o /dev/null -D - "$BASE/account/orders"
curl -sS -o /dev/null -D - -X POST "$BASE/api/public/list"

# Check separate language variants, using an endpoint that really sets Vary.
curl -sS -o /dev/null -D - -H 'Accept-Language: pl' "$BASE/translations/home"
curl -sS -o /dev/null -D - -H 'Accept-Language: pl' "$BASE/translations/home"
curl -sS -o /dev/null -D - -H 'Accept-Language: en' "$BASE/translations/home"

# A/B: only if the origin varies by X-Experiment and this is genuinely public.
curl -sS -o /dev/null -D - -H 'X-Experiment: A' "$BASE/experiment"
curl -sS -o /dev/null -D - -H 'X-Experiment: B' "$BASE/experiment"

If a command prints no diagnostic header, do not assume a HIT or PASS. Re-run with diagnostics enabled or inspect Cache/Traffic counters and origin access logs. Compare two requests to the same scheme, host, path, query and Vary header values. Changing an identity, method or URL changes the result. Avoid curl -k as a testing habit: verify the real TLS certificate.

Minimal scenario matrix for the graphical rule tester

Test Request input Mock origin response Expected rule-level decision
Catalog lookup GET /catalog/item/1 200, Cache-Control: public, max-age=120 Request lookup; backend TTL=120, grace=20.
Logged-in user GET /catalog/item/1, Cookie session=abc 200, Cache-Control: private Request PASS; no public storage.
CDN-only GET /catalog/item/1, Cookie __cf_bm=abc 200, public After CDN recipe: Cookie removed; lookup eligible.
Mixed cookies GET /catalog/item/1, Cookie __cf_bm=abc; session=abc 200, public Request PASS; session preserved.
Public API GET /api/public/list 200, JSON, public Lookup; backend TTL 15 and grace 5.
Private API GET /api/private/me 200, private Request PASS.
API mutation POST /api/public/list 200, JSON, public Request PASS.
Multi-language GET /translations/home, Accept-Language pl 200, public, Vary: Accept-Language Eligible variant for pl.
SSE GET /events 200, text/event-stream PASS.
404 GET /catalog/missing 404 TTL rule not enough to store.
Backend failure GET /catalog/item/1 503 503 not storable; separate stale policy may apply.
Tracking-query source GET /landing?utm_source=x 200, public Restricted import warning; review stripped query representation.

The tester previews the cache rules, including unsaved rules in the active editor. It does not simulate all unsaved global/per-Vhost cache configuration, is not connected to the origin and cannot prove a real HIT.

G. Common mistakes and missing functionality

Symptom or attempted VCL Why it fails or is dangerous Correct approach
Import looks successful but nothing changes Import previews rules; warnings require manual acceptance, and rules still need saving Inspect converted graph, approve reviewed warnings, save, test live
return(hash) but every request is BYPASS Cache disabled, credential/route restriction, response no-store/Set-Cookie, request policy, size limits, etc. Check global + Vhost flags and actual response headers
A MISS never becomes HIT MISS may not be stored; TTL 0, invalid Vary, origin private, Set-Cookie, status != 200 Inspect reason and origin headers; do not force public without proof
unset req.http.Cookie on a header containing session Removes all cookies, including session identity Use anchored entire-header technical allowlist or PASS
set req.http.Cookie = regsuball(...) Not imported Graphical Strip cookies / Keep names with reviewed scope
set req.url = regsub(...) with arbitrary pattern Not implemented Use native path/location routing or the graphical query action
client.ip ~ my_acl, return(purge), return(synth) Unsupported VCL importer actions Use native ACL/security/purge/route/error configuration
set beresp.ttl = 1h for a 404 Storage only supports HTTP 200 No negative-cache feature in this version
unset resp.http.Vary to merge variants Changes client response, not stored key; breaks downstream caches Fix origin Vary or use strict native public-static Cookie exception
unset beresp.http.Cache-Control or Set-Cookie to force HIT Can turn private data into shared content Restore origin privacy; do not rewrite session responses
hash_data on request header without downstream Vary RustProxy partition and client/CDN partition differ Have the origin send all true Vary members
Need request-body parsing, ESI, backend directors, VMOD, cache-specific custom logging No VCL interpreter/VMOD/body hook Configure native features where supported or handle at origin
Docker vhost does not appear in global scope Discovery/configuration may have changed; cache target list depends on active inventories Recheck Docker agent inventory, publish/assignment and Cache target scope

H. Change-management checklist

  • Select global, manual Vhost or Docker Vhost scope; compare inherited and local rule precedence.
  • Confirm backend privacy contract for every URL and Cookie combination.
  • Confirm only GET/HEAD are eligible; session and Authorization requests bypass.
  • Check HTTP 200 status, freshness, validators, size, response Cache-Control, Set-Cookie and complete Vary.
  • Import without unexpected warnings; separately approve any restricted conversion after inspecting graph.
  • Save the rules, then test real requests and variants (not only the rule tester).
  • Recheck after upstream changes, CDN changes, Docker container recreation and caching-mode changes.
  • Invalidate affected existing cache objects when changing privacy, key or Vary policy.

Further references

  • Exact VCL support matrix: supported, restricted, graphical-only, intentional exclusions and absent features.
  • VCL import semantics: stage order, header edits, syntactic limits, strict vs compatible behavior.
  • HTTP cache: freshness, static options, Vary matching, diagnostics, HOT/COLD, purge and stale handling.
  • Docker discovery: Docker inventory and saved vhost publication lifecycle.
  • Cache API: configuration and cache endpoints.

Validation scope: These are source-reviewed operator examples, not evidence of a full Rust compiler/proxy traffic test. Revalidate against the actual binary and origin before production use.