请求创建VCL规则:仅缓存/order/{x}/{y}层级的URL页面
Varnish VCL Rule to Cache Exact /order/{x}/{y} Paths Only
Hey there, let's get this Varnish caching rule sorted for you. You need to cache URLs that exactly follow the /order/{x}/{y} format (where x and y can include alphanumeric characters and special symbols), while leaving /order/{x} and any deeper nested paths (like /order/{x}/{y}/{z}) un-cached. Here's a solid implementation for your VCL:
sub vcl_recv { # Cache only URLs matching the exact /order/{x}/{y} pattern if (req.url ~ "^/order/[^/]+/[^/]+$") { # Mark this request as cacheable set req.http.X-Cacheable = "yes"; # Set a custom TTL (adjust this to your needs, e.g., 30m for 30 minutes) set req.ttl = 1h; } else { # Bypass cache for all other /order-related paths if (req.url ~ "^/order/") { return (pass); } } } # Optional: Configure backend response caching behavior sub vcl_backend_response { if (bereq.http.X-Cacheable == "yes") { # Set the TTL for cached responses set beresp.ttl = 1h; # Remove cookies to avoid per-user cache variations (only do this if cookies aren't needed for these pages) unset beresp.http.Set-Cookie; } }
Breakdown of the Rule:
The regex
^/order/[^/]+/[^/]+$is critical here:^/order/anchors the match to the start of the URL, targeting only/orderpaths[^/]+matches any sequence of characters except a slash—this captures your x and y values, including special characters like_,-,%, etc.- The trailing
$ensures the URL ends right after the second segment, which blocks deeper paths like/order/x/y/zfrom being cached.
For any
/orderpath that doesn't match the exact two-segment pattern (like/order/xor/order/x/y/z), we usereturn (pass)to skip caching entirely—these requests will go straight to your backend every time.
Key Notes:
- Test the regex: Make sure it works with your actual URL patterns. You can test locally by sending sample requests to Varnish and checking cache hits/misses, or use Varnish's built-in debugging tools.
- Adjust TTL: The
1h(1 hour) TTL in the example is just a starting point—tweak this to match how often your/order/{x}/{y}content changes. - Cookies: If your
/order/{x}/{y}pages require cookies (e.g., for user-specific data), remove theunset beresp.http.Set-Cookieline. Keep in mind that cookies will make Varnish cache unique copies for each user, which might reduce cache efficiency.
内容的提问来源于stack exchange,提问作者Aj K
相关产品推荐
相关产品推荐

