Send request header from Varnish to backend server - varnish

Is it at all possible to send some headers from varnish end to backend server during a fetch? I need this to identify a certain scenario in my backend.
Which subroutine should I use and how?

You can define custom backend request headers in the vcl_backend_fetch subroutine.
Here's an example:
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = "80;
}
sub vcl_backend_fetch {
set bereq.http.my-custom-header = "my-custom-value";
}
Keep in mind that vcl_backend_fetch is backend-side subroutine that uses the bereq object to obtain client request information.
See https://www.varnish-software.com/developers/tutorials/varnish-configuration-language-vcl/#backend-request-variables for more information about backend request variables.

Related

My varnish config doesn't seem to be working properly

I'm very new on varnish and I've a business on my hands recently. It's a local magazine website http caching (Tech Stack is Javascript + PHP). I'm trying to use varnish 4 for caching the website. What they want me to do is; any new articles should be appeared on FE immediately, any deleted articles should be erased from the FE immediately, any changes on website's current appereance should be applied directly (changing articles' current locations, they can be dragged anywhere on the website based on articles' popularity change.) and finally any changes on existing articles should be applied to website immediately. As you see on the config below, in sub vcl_recv block I tried to use return(purge) for POST requests, because new articles and article changes is applied via POST request. But it doesn't work at all. When I try create a new dummy content or make changes on existing articles, it's not purging the cache and showing the fresh content even if POST request is successful. Also, on the BE side, I tried to use if (beresp.status == 404) for deleted articles, but it doesn't work too. When I delete the dummy article I created, it's not being deleted too, I'm still seein the stale content. How should I change my config to get all these things done? Thank you.
my varnish config is ;
import directors;
import std;
backend server1 {
.host = "<some ip>";
.port = "<some port>";
}
sub vcl_init {
new bar = directors.round_robin();
bar.add_backend(server1);
}
sub vcl_recv {
set req.backend_hint = bar.backend();
if (req.http.Cookie == "") {
unset req.http.Cookie;
}
set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|has_js)=[^;]*", "");
if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
unset req.http.cookie;
}
if (req.url ~ "\.*") {
unset req.http.cookie;
}
if (req.method == "POST") {
return(purge);
}
}
sub vcl_deliver {
# A bit of debugging info.
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
}
else {
set resp.http.X-Cache = "MISS";
}
}
sub vcl_backend_response {
set beresp.grace = 1h;
set beresp.ttl = 120s;
if (bereq.url ~ "\.*") {
unset beresp.http.Set-Cookie;
unset beresp.http.Cache-Control;
}
if (bereq.method == "POST") {
return(abandon);
}
if (beresp.status == 404) {
return(abandon);
}
return (deliver);
}
No need to use the director if you only have one backend. Varnish will automatically select the backend you declared if there's only 1 backend.
Purging content
The POST purge call you're doing is not ideal. Please have a look at the following page to learn more about content invalidation in Varnish: https://varnish-cache.org/docs/6.0/users-guide/purging.html#http-purging
The snippet on that page contains an ACL to protect your platform from unauthorized purges.
It's important to know that you'll need to create a hook into your CMS or your MVC controller, that does the purge call.Here's a simple example using curl in PHP:
$curl = curl_init("http://your.varnish.cache/url-to-purge");
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PURGE");
curl_exec($curl);
As you can see, this is an HTTP request done in cURL that uses the custom PURGE HTTP request method. This call needs to be executed in your good right after the changes are stored in the database. This post-publishing hook will ensure that Varnish clears this specific object from cache.
VCL cleanup
The statement below doesn't look like a reliable way to remove cookies, because the expression will remove cookies from all pages dat contain a dot:
if (req.url ~ "\.*") {
unset req.http.cookie;
}
The same applies to the following statement coming from the vcl_backend_response hook:
if (bereq.url ~ "\.*") {
unset beresp.http.Set-Cookie;
unset beresp.http.Cache-Control;
}
I assume some pages do actually need cookies to properly function. An admin panel for example, or the CMS, or maybe even a header that indicates whether or not you're logged in.
The best way forward is to define a blacklist or whitelist of URL patterns that can or cannot be cached.
Here's an example:
if(req.url !~ "^/(admin|user)" {
unset req.http.Cookie;
}
The example above will only keep cookies for pages that start with /admin or /user. There are other ways as well.
Conclusion
I hope the purging part is clear. If not, please take a closer look at https://varnish-cache.org/docs/6.0/users-guide/purging.html#http-purging.
In regards to the VCL cleanup: purging can only work if the right things are stored in cache. Dealing with cookies can be tricky in Varnish.
Just try to define under what circumstances cookies should be kept for specific pages. Otherwise, you can just remove the cookies.
Hope that helps. Good luck.
Thijs

Varnish: Making each API keys objects cache separately

I have Varnish 4 installation where I select a backend based on an API-key in the header of each request, such as (we are in vcl_recv):
if (req.url ~ "/content") {
# Check for presence of X-Api-Key header
if ((! req.http.X-Api-Key) || ((! req.http.X-Api-Key ~ "prod-") && (! req.http.X-Api-Key ~ "test-"))) {
return(synth(403,"Access Denied - API key missing or invalid."));
}
if (req.http.X-Api-Key ~ "prod-") {
set req.backend_hint = PROD.backend();
}
if (req.http.X-Api-Key ~ "test-") {
set req.backend_hint = TEST.backend();
}
}
However, objects fetched from the PROD backend can get delivered to requests to the TEST backend, if their TTL is not expired, and vice versa.
How do I make sure that content from each backend is isolated from the other?
This one is easy. Since you want the cache to vary by specific header, you should tell Varnish about it. So either make your backend send Vary: X-Api-Key (best route), or have Varnish hash on that header's value:
sub vcl_hash {
if (req.http.X-Api-Key) {
hash_data(req.http.X-Api-Key);
}
}

Can Varnish backend be specified by stand-alone app?

Currently we have 3 applications (varnish backends):
Eshop
CMS
Routing - app which returns status code of which backend should be chosen to hit.
The main idea between this is that we have the same domain for Eshop and CMS. And all links are stored in MySQL database. So to decide where should varnish hit we are using some routing app.
If we are hitting routing backend in the vcl_recv we are checking status in vcl_backend_response and switching the backend like that:
sub vcl_backend_response {
if (591 == beresp.status) {
set bereq.backend = eshopDirector.backend();
return (retry);
} elsif (592 == beresp.status || 593 == beresp.status || 594 == beresp.status) {
set bereq.backend = cmsDirector.backend();
return (retry);
}
}
After retry we are not caching results because vcl_recv stage is not hit again to identify if results has to be retrieved from the cache or from the backend itself.
So the question here, is there any way to identify which backend has to be used from vcl_recv stage, to get cached results afterwards?
Maybe it's possible to make CURL request from there to get status from the routing app and handle it accordingly?

Varnish Cached Object Time

How can we get the the time of the cached object in varnish.
My requirement is something like, say if object is in cache for 5 mins and for a specified ip, I want to server the content from backend but not from cache.
You can setup your vcl so it will always miss when certain headers are set or when the request comes from a certain browser
in your vcl_recv set
sub vcl_recv {
if (req.http.Cache-Control ~ "no-cache" && client.ip ~ editors) {
set req.hash_always_miss = true;
}
}
https://www.varnish-cache.org/trac/wiki/VCLExampleEnableForceRefresh

Varnish 3 - how to set maximum age in http headers

I am using Varnish 3.0.3 and to use it to leverage browser caching by setting a maximum age in the HTTP headers for static resources. I tried adding the following configuration to default.vcl:
sub vcl_fetch {
if (beresp.cacheable) {
/* Remove Expires from backend, it's not long enough */
unset beresp.http.expires;
/* Set the clients TTL on this object */
set beresp.http.cache-control = "max-age=900";
/* Set how long Varnish will keep it */
set beresp.ttl = 1w;
/* marker for vcl_deliver to reset Age: */
set beresp.http.magicmarker = "1";
}
}
sub vcl_deliver {
if (resp.http.magicmarker) {
/* Remove the magic marker */
unset resp.http.magicmarker;
/* By definition we have a fresh object */
set resp.http.age = "0";
}
}
This is copied from https://www.varnish-cache.org/trac/wiki/VCLExampleLongerCaching . Maybe I just made a typo. On restart of Varnish, it no longer worked.
I have two questions. Is this the correct way to do it for Varnish 3? If so, what am I doing wrong? Secondly, is there a way to test the Varnish configuration file, before a restart? Something along the ways of what Apache has with "/sbin/service httpd configtest". That catches mistakes before going live. Thank you.
Yes, in general this is the way of overriding the backend's TTL.
Remove beresp.http.expires, set beresp.http.cache-control, set beresp.ttl.
beresp.cacheable is a 2.[01]-ism. The same test in 3.0 is to check that beresp.ttl > 0.
A small tip is to store your magic marker on req.http instead, then you don't have to clean it up before handing the object to the client.
With regards to testing a configuration file, you can call the VCL compiler directly with "varnishd -C -f /etc/varnish/default.vcl" for example. If your VCL is faulty you get the error message, if the VCL is valid you get a few pages with generated C code.

Resources