Laravel sets a cookie even if the user is not logged in. This causes Varnish to send all requests to the server. I met some people ( http://abeak.blogspot.co.uk/2014/12/caching-laravel-with-varnish.html ) using Session Monster , which sets the header X-No-Sessionif the user is not authenticated. This is a Laravel 4 package, so I created instead a middleware that sets the title if the user is not out of date.
I can't figure out how to get Larnish to send backend requests only when the header is not set. I would really appreciate any guidance!
EDIT:
This middleware sets the header X-No-Sessionif the user is not logged in:
<?php
namespace App\Http\Middleware;
use Closure;
use Session;
class StripSessionsIfNotAuthenticated
{
public function handle($request, Closure $next)
{
if(auth()->check()) {
return $next($request);
}
return $next($request)->header('X-No-Session', 'yeah');
}
}
Then I converted VCL to a related article in VCL V4:
vcl 4.0;
backend default {
.host = "127.0.0.1";
.port = "8080";
}
sub vcl_recv {
if (req.url ~ "^/auth" || req.method == "POST" || req.http.Authorization) {
return (pass);
}
if (req.url ~ "\.(png|gif|jpg|css|js|ico|woff|woff2|svg)$") {
unset req.http.cookie;
return (hash);
}
if (req.http.X-No-Session ~ "yeah" && req.method != "POST") {
unset req.http.cookie;
}
return (hash);
}
sub vcl_backend_response {
set beresp.ttl = 1d;
if (bereq.method == "GET" && bereq.url ~ "\.(png|gif|jpg|css|js|ico|woff|woff2|svg)$") {
unset beresp.http.set-cookie;
set beresp.ttl = 5d;
}
return (deliver);
}
sub vcl_deliver {
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
} else {
set resp.http.X-Cache = "MISS";
}
}
Chris source
share