Varnish-Cache, VCL: 301 Redirect

A typical 301 redirect is usually configured in your apache vhost file. But you can also use varnish-cache to perform the redirect without passing the request to your backend.

Apache Redirect Example

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteCond %{HTTP_HOST} ^(www\.)?old\.dmsp\.de$
   RewriteRule ^(.*)$ [R=301,L]

Varnish Redirect Example

sub vcl_recv {
   if ( ~ "^(www\.)?old\.dmsp\.de") {
      set = "";
      error 301;

sub vcl_error {
   if (obj.status == 301 && == "") {
      set obj.http.Location = "";
      set obj.status = 301;
      return (deliver);

One important difference between realizing a 301 redirect with Apache or Varnish is that you will not be able to cache a 301 when using Varnish for the redirect (because you do not generate a cacheable object). When using Apache for the redirect, you can easily configure Apache to send a ‚max-age‘ header with the 301 status reply and obviously you have a cacheable object (the ‚Location:‘ header is only a part of it). Varnish will interpret the ‚max-age‘ according to RFC2616 and will set the TTL of the object to 120 seconds (which is easily modifiable from inside the VCL).