Varnish 4配置:如何让浏览器显示Apache错误而非Varnish后端获取失败
Hey there, great question—yes, Varnish 4 absolutely supports this! By default, Varnish replaces backend error responses (like 4xx/5xx codes from Apache) with its own generic messages (including that "backend fetch failed" line), but a few simple VCL tweaks will let you pass through Apache's native error pages directly to the browser.
Here's how to set it up, depending on the scenario:
1. Pass Through Apache's Direct Error Responses
When Apache itself returns an error (like a 404 Not Found or 500 Internal Server Error), you can tell Varnish to skip its default error handling and deliver the Apache response as-is. Add this to your VCL file in the vcl_backend_response subroutine:
sub vcl_backend_response { # Capture all 4xx and 5xx errors from the backend if (beresp.status >= 400 && beresp.status <= 599) { # Disable ESI processing (not needed for error pages) set beresp.do_esi = false; # Optional: Add a header to confirm the error came from Apache set beresp.http.X-Backend-Error-Source = "Apache"; # Deliver the raw backend response instead of triggering Varnish's error handler return (deliver); } }
This tells Varnish to take Apache's error response (including its custom HTML, headers, etc.) and send it straight to the client without modification.
2. Handle Varnish-Triggered Backend Failures
If Varnish can't reach Apache at all (resulting in a 502 Bad Gateway or similar), it won't have an Apache error response to pass through. In this case, you can configure Varnish to fetch Apache's custom error page directly when this happens. Add this to the vcl_error subroutine:
sub vcl_error { # Target Varnish-generated 5xx errors (backend unreachable, timeout, etc.) if (obj.status >= 500) { # Point to your Apache backend (replace with your actual backend name) set req.backend_hint = apache_backend; # Request the corresponding error page from Apache (adjust the path to match your setup) set req.url = "/custom-errors/" + obj.status + ".html"; # Fetch the error page and deliver it to the client return (fetch); } # For non-5xx errors, you can either deliver Varnish's default or add similar logic return (deliver); }
Notes for This Setup:
- Make sure you replace
apache_backendwith the name of your Apache backend defined in the VCL. - Ensure Apache has custom error pages at the path you specify (e.g.,
/custom-errors/502.htmlfor 502 errors). - Test this thoroughly by simulating backend downtime to confirm the correct error page loads.
Final Steps
After updating your VCL, recompile and reload Varnish to apply the changes:
varnishreload /etc/varnish/default.vcl
That's it! Your clients will now see Apache's native error messages instead of Varnish's generic ones, whether the error comes directly from Apache or Varnish can't reach the backend.
内容的提问来源于stack exchange,提问作者Giri Profile

