Sometimes we need restrict access to site that cached by Varnish with basic HTTP authentication.
Basic method is enable it on backend (Apache, nginx, lighttpd or other web-server). But after the first correct request, it will be cached on Varnish and all other clients requests would be without authentication.
Solution for this situation is pass all request with authentication to backend with next statement:
1 2 3 4
As we remember, caching still required for this site. So, statement above is not suitable for our conditions.
Good workaround is to check HTTP authentication at the Varnish.
Well then do it in VCL.
On vcl_recv section we will check a authorization header and invoke a 401 error if header is not present:
1 2 3 4
where Zm9vOmJhcgo= is a base64 encoded string of “http-user:http-password”. In this example it is a foo:bar.
To get encoded string you may use base64 console command:
or use some other tool.
Next, on vcl_error section we need to create a error handler for 401 code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Adding this both snippets to your VCL enables HTTP authorization on Varnish and caching still present, so you are able to develop or debug your site.
Multiple users and password can be set with && statement on header check:
1 2 3 4 5