Linux – How to get Apache 301 redirects working with Varnish

301-redirectapache-2.2linuxvarnish

I'm trying to add a number of redirects from old domains to new domains which I have done before using simple 301 redirects in my vhost files like:

<VirtualHost *:8080>
  ServerName olddomain.com
  ServerAlias www.olddomain.com
  Redirect 301 / http://www.newdomain.com/
</VirtualHost>

However this isn't working in my vhost file and I am assuming its because of the Varnish server running in front of Apache but not sure how to fix it. The main site, in the same vhost file, is using the same port, ex:

<VirtualHost *:8080>
  ServerName www.newdomain.com
  ...

</VirtualHost>

What am I missing? I've tried working with the varnish configuration file to add the redirects in there but ran into issues — is that the best option?

Best Answer

I'm still not clear why the apache vhost above wasn't being recognized, perhaps due to something in the varnish vcl file that intercepted it but I was able to solve this eventually by adding a redirect there, following the instructions here https://www.varnish-cache.org/trac/wiki/VCLExampleRedirectInVCL

sub vcl_recv {
    if (req.http.host ~ "^(www\.)?oldexample\.com$") {
        error 750 "http://www.example.com/newlocation";
    } else if (req.http.host ~ "^(www\.)?ancientexample\.com$") {
        error 750 "http://newsite.com/ancient"
    }
 }

 sub vcl_error {
   if (obj.status == 750) {
       set obj.http.Location = obj.response;
       set obj.status = 302;  
       return(deliver);
   }
 }