测试Varnish缓存规则:编写test.vtl验证配置失败求助
Let's break down why your test is failing and fix it step by step.
1. Critical: Missing X-Path Header in Backend Requests
Your cache rule checks bereq.http.X-Path, but this header doesn’t exist in backend requests by default. Unless you explicitly set this header in your VCL (e.g., in vcl_recv or vcl_backend_fetch), the condition will never match—so the Cache-Control header won’t be applied at all.
If your goal is to target JS/CSS files based on their URL path, you should modify your rule to use bereq.url instead (this refers directly to the backend request’s URL path):
sub vcl_backend_response { if (bereq.url ~ "[a-z0-9]+\.(js|css)$") { set beresp.http.Cache-Control = "max-age=259200"; } }
2. Fixing Your test.vtl File
Your original test was missing key components: loading your custom VCL, defining a backend, and asserting the expected response header. Here’s a complete, working test file:
varnishtest "Verify Cache-Control for JS/CSS files" # Define a dummy backend that returns a basic CSS response server s1 { rxreq txresp -hdr "Content-Type: text/css" } -start # Load Varnish with your custom rule and connect to the dummy backend varnish v1 -vcl+backend { backend default { .host = "${s1_addr}"; .port = "${s1_port}"; } sub vcl_backend_response { # Updated rule using bereq.url instead of X-Path if (bereq.url ~ "[a-z0-9]+\.(js|css)$") { set beresp.http.Cache-Control = "max-age=259200"; } } } -start # Send request and validate the response header client c1 { txreq -url "/content/css/main.min.aer234vcvb.css" rxresp # Assert that Cache-Control is set to the expected value expect resp.http.Cache-Control == "max-age=259200" } -run
3. Running the Test Correctly
Execute the test using the varnishtest command (don’t pass client code directly as an argument):
varnishtest test.vtl
4. If You Really Need the X-Path Header
If you have a specific reason to use bereq.http.X-Path, add code to set this header in your VCL. For example:
sub vcl_recv { # Set X-Path header from the client request URL set req.http.X-Path = req.url; } sub vcl_backend_fetch { # Pass the X-Path header to the backend request set bereq.http.X-Path = req.http.X-Path; } sub vcl_backend_response { if (bereq.http.X-Path ~ "[a-z0-9]+\.(js|css)$") { set beresp.http.Cache-Control = "max-age=259200"; } }
Update your test.vtl to include these additional VCL blocks, and the test should work as expected.
内容的提问来源于stack exchange,提问作者basante

