28 KiB
VCL import: supported instructions and exact effects
This guide describes the VCL subset implemented by RustProxy 0.42.1, not the full Varnish Configuration Language. It is based on the VCL importer and cache-rule engine. Importing VCL converts statements into graphical cache rules (which must then be saved); RustProxy does not execute arbitrary VCL text at request time. Unsupported instructions may be skipped with warnings or cause a parse error; they are not executed as Varnish code. In the graphical importer, warnings pause conversion: no rules are added until you explicitly choose Add partial import (reviewed). Even after adding, you must separately save the configuration. The read-only VCL export for ordinary flat rules is a human-oriented preview, not a lossless backup or a guaranteed re-importable VCL program. Structured VCL imports use a JSON preview/export that preserves their control flow.
For a short operational reference inside the panel, open Cache & VCL guide from Settings → Cache, the ordinary Vhost → Cache editor or Docker vhosts → Cache. The same modal works in all three places; example VCL is pasted into the importer of the editor that opened the guide, and the modal labels that scope. The modal shows the current compatibility-mode, fallback-TTL and grace settings, explains Vary and header mutations with examples, and identifies unsupported Varnish hooks. It complements this exact syntax reference; it does not execute VCL or save settings.
For the complete reference to all 42 quick-rule templates (conditions, stages, defaults, cookie/session safety, TTL and testing), see the Cache rule template library. These graphical presets are distinct from directly importable VCL. For an expanded implemented / restricted / graphical-only / intentionally excluded / not implemented inventory, consult the complete VCL support matrix. For practical production scenarios, 12 copyable VCL examples, HTTP traffic outcomes, a curl validation plan and troubleshooting, use the VCL traffic cookbook (also available from the embedded Reader). It names each supported hook, variable and return action and the deliberate HTTP/security boundaries.
Where to import, rule order and activation
Since 0.42.0, optional HTTP policy rules can cooperate with these
rules. Policy request edits run before vcl_recv/vcl_hash, policy backend
response edits run after existing beresp edits but before cache planning,
policy delivery runs after vcl_deliver, and after_response runs after
compression and legacy dynamic headers. Existing VCL order, local-over-global
priority and terminal return semantics are unchanged. Either engine's explicit
pass wins over lookup; existing VCL TTL/grace assignments take precedence over
policy assignments. New policy Global → Vhost → Location ordering does not
replace the VCL ordering described below.
- Settings -> Cache -> Rules: global cache rules, optionally targeted to particular vhosts.
- Vhosts -> Cache -> Cache rules for this vhost: rules for one vhost (ordinary or Docker-generated). Ignore global cache rules disables the global rules for that vhost.
- Imported rules and graphical rules use the same engine. Within each stage, vhost rules run first, followed by applicable global rules. A vhost edit to the same header or supported scalar setting wins over a conflicting global edit. In one scope, later matching edits win unless
stop/return(...)terminates the stage. - A terminal
return(hash)ends normalvcl_recvprocessing but does not skipvcl_hash. A terminalreturn(pass)skips lookup andvcl_hash. A return/stop does not skip the other, independent response/deliver stages. - Regular cache admission still requires enabled global/vhost caching, an eligible route, method, request policy and response. A
return(hash)cannot turn on a disabled cache or overrideAuthorization/access controls. Supported request header/cookie/query rewrites and backend header edits can still affect an ordinary reverse-proxy response even when cache storage is disabled; deliver-stage edits apply to the final response on HIT, MISS and BYPASS. These rules do not apply to embedded Web Server sources or RustProxy's administration/control-plane responses.
Supported VCL statements
| Hook | Recognized VCL syntax | Actual effect and limits |
|---|---|---|
vcl_recv |
return(pass); |
Stops request processing for the matching path; bypasses shared cache. An explicit pass is never relaxed by global cache options. |
vcl_recv |
return(cookie_pass); |
RustProxy extension (Cookie/session guard): like return(pass) for pages, but a GET/HEAD for a configured static extension may still reach the cache when Ignore request cookies for static files is on and no other rule would pass the same request. The branch must test req.http.Cookie (non-negated); otherwise the import warns and skips it. See decision precedence. |
vcl_recv |
return(hash); or return(lookup); |
Stops vcl_recv and requests a cache lookup. In compatibility mode, may admit a GET/HEAD carrying Cookie (with cookie-partitioned variants); other protections remain. |
vcl_recv |
unset req.http.Cookie; |
Removes the whole request Cookie header, including what is forwarded to the origin. |
vcl_recv |
remove_req_cookies("parent_analytics", "SESS*"); |
RustProxy extension: removes exact-name cookies or case-sensitive prefixes marked by one trailing * before later rules, cache lookup and origin forwarding. Remaining session cookies are not removed and can still trigger BYPASS. Not standard Varnish VCL. |
vcl_recv |
set req.http.X-Device = "mobile"; / unset req.http.X-Tracking; |
Sets/removes a safe request header before later conditions, vcl_hash, cache policy and the forwarded origin request. Assignments are constant strings, and a per-vhost edit takes priority over a conflicting global edit. Authentication, identity, request cache policy and transport headers are protected (see below). |
vcl_recv |
`set req.url = regsuball(req.url, "([?&])(utm_[^=&]* | gclid)=[^&]*", "\1");` |
vcl_hash |
hash_data(req.http.X-Name); |
Adds one request header's value to RustProxy's internal variant key. It does not automatically add Vary for downstream caches. |
vcl_hash |
hash_data(req.url); / hash_data(req.http.Host); |
Accepted as built-in operations with no additional rule: URL/query and normalized Host are already part of the RustProxy key. Other expressions are not imported. hash_data in vcl_recv is rejected with a warning. |
vcl_backend_response / vcl_fetch |
set beresp.ttl = 60s; and set beresp.grace = 30s; |
Configures cache freshness/grace, within RustProxy limits and policy. Units: ms, s, m, h, d, w, y (rounded to whole seconds). Does not automatically rewrite the browser's Cache-Control. |
vcl_backend_response / vcl_fetch |
set beresp.uncacheable = true; / = false; |
RustProxy-specific difference: true disables storing; false reverses an earlier rule-imposed no-store decision. Varnish itself ignores resetting beresp.uncacheable from true to false. In RustProxy, false does not ignore origin private, no-store, Set-Cookie or other cache admission restrictions. A vhost false overrides conflicting global true. |
vcl_backend_response / vcl_fetch |
set beresp.http.X-Name = "literal"; |
Replaces the named origin header before cache admission and before delivery. Only a single quoted constant string is supported, on an allowed header. |
vcl_backend_response / vcl_fetch |
unset beresp.http.X-Name; |
Removes the named origin header before cache admission and delivery. |
vcl_backend_response / vcl_fetch |
unset beresp.http.Set-Cookie; |
A special dedicated action, which removes the origin's Set-Cookie before cache policy. Only safe for genuinely public responses. |
vcl_backend_response / vcl_fetch |
return(pass);, return(hit_for_pass); or return(uncacheable); |
Marks the response as not storable; does not create Varnish hit-for-pass markers. |
vcl_backend_response / vcl_fetch |
return(deliver); |
Stops the remaining rules in that response hook. |
vcl_deliver |
set resp.http.X-Name = "literal"; |
Sets/replaces the named header only on the outgoing response. Does not change the cache's stored object or variant key. |
vcl_deliver |
unset resp.http.X-Name; |
Removes the named header only from the outgoing response, including an HIT. |
vcl_deliver |
return(deliver); |
Stops further deliver-stage rules on the matching path. |
For set and unset header instructions, HTTP header names are case-insensitive. Quoted strings accept \" and \\ escapes; regex escapes such as \s and backreferences such as \1 are kept literally. Malformed statements with extra operands are warned about and skipped, rather than silently treating their prefix as a valid action. Unterminated quoted strings and block comments reject the import. Valid headers and values are checked when a rule is compiled. The importer reports unsupported/invalid statements as warnings (skipped) or parsing errors (import rejected), rather than running them as Varnish code. A rejected header edit no longer discards adjacent valid statements, and long supported action blocks are split at the rule action limit. For repeated header fields, set replaces the entire field (not one value); unset removes all occurrences of that field. Assigning "" creates an empty field, which is not the same as removing it. Neither action merges individual comma-separated Vary members. The panel also offers graphical-only actions such as Set header if missing, Ignore backend Cache-Control, cookie allowlists and explicit query-parameter filtering; do not assume those actions have a one-to-one VCL syntax.
Request header changes: scope and safeguards
sub vcl_recv {
if (req.url ~ "^/catalog") {
unset req.http.X-Tracking;
set req.http.X-Device = "mobile";
return(hash);
}
}
sub vcl_hash {
hash_data(req.http.X-Device);
}
Both header edits are visible to later matching rules, the hash calculation and the origin. They also run on cache-disabled reverse-proxy routes (without enabling cache). They do not rewrite the client's original Vary requirements: if the response varies by X-Device, include it in beresp.http.Vary or configure it at the origin. A later unset is different from setting an empty string.
Protected request headers cannot be set or removed by general request rules: Authorization, Cookie (except dedicated whole-header unset or selective remove_req_cookies(...) actions), Cache-Control, Pragma, Host, range/precondition headers (If-*, Range), forwarding and origin identity headers (Forwarded, Via, X-Forwarded-*, X-Real-IP, X-Client-IP, CF-Connecting-IP, True-Client-IP), Proxy-*, Sec-*, X-RustProxy-*, Content-Type, Expect and the protected transport/body header list below. Rejected edits are warned about and never silently applied. Do not assume imported VCL can change authentication or request-cache restrictions.
The query-removal conversion accepts only the supported captured-separator regsuball pattern. Every such conversion emits a warning, because removing parameters with RustProxy's parser can normalize separators differently from a regex replacement. Variable-name classes such as utm_[a-z]+ are approximated by a prefix wildcard; value patterns ending in [^&]+ may preserve empty values that strip_query removes. Review generated parameters and warnings if byte-exact URL behavior matters. Other URL rewrites are deliberately not guessed from keywords such as utm_.
Recognized conditions and expressions
The corrected 0.42.0 importer records explicit branch selection. Each
if/elsif/else chain chooses its branch once when execution reaches it.
Changing or unsetting a condition's header inside that branch does not enter
its else or skip the remaining nested/tail statements. A later, independent
condition still reads the current, possibly modified headers. The same rule
applies in request, hash, backend-response and delivery hooks.
Upgrade existing imports: saved flat rules from an older importer retain their existing behavior. Their JSON no longer contains enough information to recover the original branch boundaries. Re-import the original VCL with 0.42.0, review the draft tester, replace the old converted rules and save. Do not append the new import while leaving the old actions enabled. Native graphical rules do not require conversion.
| Form | Example | Notes |
|---|---|---|
| URL, method, request headers | req.url ~ "^/assets/", req.method == "GET", req.http.Cookie |
req.url includes path and query; an unqualified request header tests presence. bereq.url and bereq.http.X are accepted as rule-request aliases. |
| Backend/delivery status and headers | beresp.status == 200, beresp.http.Content-Type ~ "^text/", resp.http.X-Flag |
Evaluated against the response at the relevant stage; earlier supported header mutations are visible to subsequent conditions. |
| Comparisons | ==, !=, ~, !~ |
Equality and regex matching for supported request/response variables. |
| Status comparisons | beresp.status >= 500, resp.status < 400 |
Also accepts >, <=, ==, !=. |
| Branching | if, elsif, else, nested blocks, &&, ` |
client.ip with a Varnish ACL is not imported; the graphical rules have a client IP/CIDR condition instead. include, external modules, backend/ACL/probe definitions and custom subroutines are not loaded as executable configuration. Arbitrary functions, variables, string concatenation, dynamic header expressions, pipe, restart, purge, synth and hit-for-miss/hit-for-pass behavior are not implemented. Import is a conversion, not a promise of runtime Varnish equivalence.
Limits include 256 KiB of VCL source, 128 canonical rules per list (including
branch-entry markers), and 16 actions per rule. A branch has up to 128 OR
alternatives with 16 conditions each; an if chain has at most 16 branches.
A group permits 16 enclosing branch guards and 2,048 condition nodes in total.
The parser also limits nested blocks and unary/grouped expressions to depth 64.
Unsupported or excessive branches are skipped with warnings or rejected at
parsing/validation; review partial imports and use the graphical tester before
saving.
Saved control flow and editor operations
Fresh imports carry optional vcl_flow metadata on their canonical cache rules.
The importer generates a versioned group ID, a zero-based index, the total
count, and references to earlier branch selections in guards. A branch-entry
rule has no actions; its branches[].any contains OR alternatives, each an AND
list of ordinary rule conditions. A final [[]] predicate represents else.
Action rules use the selected branch without re-evaluating its original guard.
Selection is private to the request, hook and configured scope, including when
the same import is used locally and globally.
Keep the complete import together. The panel moves, copies, enables, disables,
removes and assigns Vhosts to the whole group. Copies receive fresh group IDs.
Branch structure is read-only in the graphical editor; edit the original VCL
and replace its import to change that structure. The JSON preview/export keeps
the metadata, whereas the ordinary flat-rule VCL preview cannot represent it.
Configuration validation rejects incomplete or reordered groups, cross-hook
references, mixed enable/scope states and invalid branch ancestry before
activation. Rules without vcl_flow retain independent sequential evaluation.
New control-flow configurations require 0.42.0 or newer. For rollback, restore the pre-upgrade configuration; deleting metadata would make guarded actions unconditional. Keep the original VCL source alongside a full JSON backup.
Vary: before or after the cache?
Vary is an allowed header for both backend (beresp) and deliver (resp) actions. The phase matters:
| VCL statement | Internal cache / stored variants | Response sent to clients and downstream proxies |
|---|---|---|
set beresp.http.Vary = "Accept-Language"; |
Replaces the origin's complete Vary field before the variant plan is built. Distinct Accept-Language requests can have separate stored variants. |
Sends the replaced Vary, unless later processing or deliver rules modify it. |
unset beresp.http.Vary; |
Drops origin-specified variant dimensions before storage. A response that actually depends on a removed dimension may be reused for the wrong client. | Removes the origin field unless safety handling re-adds Vary: Cookie/Authorization or later rules set it. |
set resp.http.Vary = "Accept-Language"; |
No change to the variant dimensions already computed/stored. | Replaces the final Vary; may incorrectly describe the cache key to a CDN. |
unset resp.http.Vary; |
No change to internal variants or HIT behavior. | Removes Vary downstream. Dangerous when the response varies by language, encoding, cookies or credentials. |
Important details:
set beresp.http.Vary = "X-Device";replaces, not appends: any previousVary: Accept-EncodingorVary: Cookieis discarded by that assignment. The importer does not support expressions such asberesp.http.Vary + ", X-Device"orregsub(beresp.http.Vary, ...)to merge values. List all required dimensions explicitly in a constant string, or configure them at the origin.Vary: *and malformedVaryprevent shared reuse. With a validVary, RustProxy uses all retained dimensions and normalizes selected header families as described in Cache.- Safety exception: when a request carrying
Cookieis explicitly allowed byreturn(hash)(or forced caching), RustProxy makes its variant cookie-dependent and can re-addVary: Cookiebefore storage/delivery even ifberesp.http.Varyremoved it. Forced credential variants can likewise addVary: Authorization. This is not a general VCL override of protected request policies. - Static-file exception:
Ignore Vary: Cookie for public static assetsmay remove just theCookiemember fromVaryonly under the documented static extension, explicitpublic, freshness and privacy checks. It does not erase other dimensions. The static-cookie options are separate from manually setting/unsettingVaryin VCL. vcl_deliverruns after variant selection. Althoughunset resp.http.Varyis accepted, using it on a variant response can make a browser/CDN store an unsafe representation. Do not removeVaryonly to increase the HIT ratio.
Example for a response that really varies only by language:
sub vcl_backend_response {
if (bereq.url ~ "^/catalog") {
set beresp.http.Vary = "Accept-Language";
set beresp.http.Cache-Control = "public, max-age=60";
unset beresp.http.X-Powered-By;
}
}
This does not claim that all catalog responses are safe to share: the application must not vary them by sessions, cookies, compression, permissions or other request headers unless those dimensions are also retained. If compression can change representation bytes, preserve the corresponding Accept-Encoding semantics.
Removing headers, Cache-Control and Set-Cookie
| Example | When removed/changed | Does it affect cache admission? |
|---|---|---|
unset beresp.http.X-Debug; |
On origin response, before storage and client delivery | Only indirectly, e.g. via metadata/policy if applicable |
unset resp.http.X-Debug; |
On final response (HIT/MISS/BYPASS) | No |
unset beresp.http.Cache-Control; |
Removes origin cache policy before storage | Yes: can remove no-cache, private or no-store constraints |
set beresp.http.Cache-Control = "public, max-age=60"; |
Replaces origin policy before storage | Yes: origin policy is evaluated as rewritten |
set resp.http.Cache-Control = "public, max-age=60"; |
Changes the client-facing header only | No: cannot make a BYPASS into a stored HIT |
unset beresp.http.Set-Cookie; |
Removes Set-Cookie via special backend rule | Yes: removes a reason to reject shared storage |
Security: rewriting or removing Cache-Control: private/no-store in vcl_backend_response, or stripping Set-Cookie, explicitly discards the origin's protection. RustProxy's storage policy sees the rewritten response. Only do this for representations proven identical for all users; never for login, account or session-dependent pages. The graphical Ignore backend Cache-Control action can likewise override origin privacy directives for RustProxy cache admission even while preserving them in downstream headers; it must be treated as an explicit policy override. Merely enabling Varnish compatibility does not strip these directives. set beresp.ttl does not by itself erase private or no-store.
The following headers are protected against general set/unset actions in both beresp.http.* and resp.http.*: Connection, Content-Length, Content-Encoding, Content-Range, Date, Keep-Alive, Proxy-Authenticate, Proxy-Authorization, Set-Cookie, TE, Trailer, Transfer-Encoding, Upgrade, Host, Alt-Svc. An attempted edit is skipped with a warning. The one exception is the dedicated unset beresp.http.Set-Cookie removal action; arbitrary set beresp.http.Set-Cookie and unset resp.http.Set-Cookie are not supported. Other proxy subsystems may also generate or normalize response headers after backend rules have run.
Example for final-response-only cleanup (does not affect cache identity, TTL or origin storage):
sub vcl_deliver {
unset resp.http.X-Debug;
set resp.http.X-Policy-Name = "catalog-public";
return(deliver);
}
Cookies and return(hash)
In compatibility mode (cache.varnish_compatible=true), return(hash) can opt in to caching eligible GET/HEAD requests with Cookie. It does not remove the Cookie header. Remaining cookie values partition the RustProxy variant, and the response includes a Cookie Vary dimension for downstream caches. This is safer than sharing all cookie-bearing requests, but reduces HIT rates. Explicit return(pass) should intercept session cookies before return(hash):
sub vcl_recv {
if (req.http.Cookie ~ "(^|; *)session=") {
return(pass);
}
if (req.url ~ "^/catalog") {
return(hash);
}
return(pass);
}
Use unset req.http.Cookie; only when the origin does not need any cookies for that route. For a Vhost that receives cookies from a parent domain, prefer the name-selective opt-in recipe: remove_req_cookies("exact_cookie_name", "SESS*"); is a RustProxy-specific extension that removes exact names or a single trailing-* prefix, preserving other cookies for later rules. Use SESS* only when the Vhost never uses that session family; see the Drupal 6 parent-domain example. The separate CDN technical-cookie policy still has its own anchored allowlist and remaining-cookie pass. Cookie does not disclose the setting Domain, so a name must be verified outside RustProxy; avoid removing a name also used by this Vhost. A graphical Strip cookies action keeps an allowlist but is not equivalent to selective removal. In strict RFC mode (cache.varnish_compatible=false), return(hash) does not bypass the request Cookie restriction. Authorization, non-GET/HEAD traffic, request no-store, access/authentication and sticky-session checks still apply.
no-cache and TTL
varnish_compatible=trueand positivecache.default_ttl_seconds(or an explicit positiveset beresp.ttl) may treat an otherwise eligible originCache-Control: no-cacheas fresh for that TTL, without requiringpublic. This is RustProxy's configured override, not vanilla Varnish's built-in behavior.varnish_compatible=falsehonorsno-cacherevalidation, including when a TTL action is present. An explicit backend header rewrite removingno-cachechanges the response policy in both modes; that is a different and potentially unsafe operation.- Backend
private,no-store,Set-Cookie, malformedVary, unsupported status, invalid headers and size bounds still block storage unless an administrator explicitly rewrites the affected cache-policy headers via trusted rules. Client/request restrictions remain separate. - Only HTTP 200 origin responses are storable in RustProxy 0.39.2. Setting
beresp.ttlfor404,301or302does not create a negative/redirect cache. The misleading 404 TTL template was removed from the graphical editor. Deliver-stage header rules can still edit those responses without making them cacheable. - Hit-for-miss / hit-for-pass and
beresp.keepare intentionally not imported. RustProxy already coalesces eligible misses and briefly remembers uncacheable fills for its collapse strategy, and independently retains validators for conditional revalidation. These are not Varnish-compatible hit-for-miss/pass objects or programmablekeepsemantics.
Test an imported rule set
- Import VCL in the appropriate global or per-vhost Rules editor. With warnings the importer does not add the converted rules automatically. Read each warning; either revise the VCL and rerun or explicitly click Add partial import (reviewed). No VCL is executed directly at runtime. The resulting rules are still unsaved until you save the settings. Closing the importer or modifying its source invalidates any outstanding parse result; an older API response cannot add rules after cancellation. Do not treat Copy as VCL as a backup/round trip; use RustProxy configuration exports for exact rules.
- Expand Test a request (two compact sections: HTTP request and backend response) in the global, ordinary-vhost or Docker-vhost Rules editor. Supply URL or path, method, Cookie/other request headers, client IP, example backend status and headers (
Cache-Control,Vary,Set-Cookie); inspect matched/suppressed rules, backend header edits, cacheability, TTL/grace and deliver actions. The global tester previews unsaved global rules with the selected vhost's saved rules; a local tester previews unsaved vhost rules with saved applicable global rules, unless Ignore global cache rules is enabled. For a path-only test the current local hostname is sent asHostif no explicit Host header was provided; full URLs and explicit Host headers win. The tester does not simulate other unsaved cache settings and does not send a request to the backend. A not-yet-saved vhost may lack its saved settings in the preview. Use real HTTP requests for final HIT/MISS verification. - Save the rules, then send the same
GETtwice (and change oneVarydimension) against a real reverse-proxy vhost. InspectX-Cache/X-Cache-ReasonorServer-Timing, depending on enabled diagnostics, plus the actual delivered headers. A response can be a MISS yet remain ineligible for storage. - Test session cookies,
Authorization, privacy directives, compressed variants, HIT versus BYPASS and global versus per-vhost conflicts before production. If the origin's behavior differs by a header, verify the correctVaryis present in both the internal storage decision and the downstream response.
See HTTP cache, Cache API, and Security for cache settings and operational limits.