Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I go about automatically redirect any link of the type to

I would like to do this for all link that hits the varnish instance (so i don't have to individually define the value for all domain that hits the server).

I tried using the following:

if( ~ "^www\.(.+)$"){
    set = regsub(, "^www\.", "");

It works, but the problem with that is it's hitting the right backend, but it's not redirecting. I understand from here: you can redirect to a url, but I am not sure how to get the "full" url from varnish to strip out the www and redirect.

Any help would be appreciated!

Thanks a lot!


share|improve this question
What you are doing there is an internal rewrite and not a redirect. In order to redirect you are going to have to send a 301 back to the client. – Patrick James McDougle Oct 24 '12 at 20:17

Varnish does not have a native mechanism for redirection from vcl_recv(). Instead you have to throw an error from vcl_recv() to be caught in vcl_error(). This is because vcl_recv() doesn't have access to the response object. You can read about how this is done. Below is my attempt at an answer in terms of your situation.

In vcl_recv():

if ( ~ "^www\.") {
  error 750 regsub(, "^www\.(.*)", "http://\1"); //Capture everything after the www. and place it after a http://

In vcl_error():

if (obj.status == 750) {
    set obj.http.Location = obj.response;
    set obj.status = 302;
share|improve this answer

vcl 4.0;

sub vcl_recv {
   if ( ~ "^([-0-9a-zA-Z]+)\.([a-zA-Z]+)$") {
    return (synth (750, ""));

sub vcl_synth {
   if (resp.status == 750) {
    set resp.status = 301;
    set resp.http.Location = "http://www." + + req.url;
share|improve this answer
Generally it is recommended to include some explanation to what your code actually does rather than just posting it as-is - could you update your post with an explanation please? – BE77Y Feb 8 at 15:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.