preload preload preload preload

URL Redirecting (301,302) in Varnish

There is no straight forward method for 301/302 URL redirection as we did with rewrite rule. But there are some situations where we need to redirect a URL on a host to some URL on different host. In this situation we need to use 301/302 redirection.  There are two ways we can implement this.

First method is to use  set req.http.host and set req.url in the vcl.conf file. Using these two methods we perform normal redirection. Using these method we will redirect the url to some other URL on the same host. For example say the URL http://example.com/error500.php will be redirect to the URL http://example.com/redirect.php. We specify 301/302 redirection to the URL http://foo.com/index.php in the redirect.php file using header method.

  • In the sub vcl_recv method use the following code.
sub vcl_recv {
   if (req.http.host ~ "example.com") {
      if (req.url ~ "error500.php") {
         set req.http.host = "example.com";
         set req.url = "/redirect.php";
      }
   }
}
  • In the redirect.php file use the following method.
<?php
header("HTTP/1.1 302 Moved Temperarly");
header('Location:http://foo.com/index.php');
exit;
?>

Second method is to use vcl_error error method. In this error method we can specify HTML tags, so using meta tags we can implement redirection. This option is available with the latest version of varnish.

  • In the sub vcl_recv method use the following code.
sub vcl_recv {
   if (req.http.host ~ "example.com") {
      if (req.url ~ "error500.php")
         error;
      }
   }
}
sub vcl_error {
        set obj.http.Content-Type = "text/html; charset=utf-8";
        if (req.http.host ~ "example.com") {
                if (req.url ~ "error500.php") {
                        synthetic {"
                                <?xml version="1.0" encoding="utf-8"?>
                                <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
                                <html>
                                        <head>
                                                <meta http-equiv="refresh" content="0;url=http://foo.com/index.php">
                                        </head>
                                </html>
                        "};
                }
        }
        deliver;
}
  • Share/Bookmark
  • Leave a Reply

    * Required
    ** Your Email is never shared