Search code examples
varnishvarnish-vcl

How to redirect all sub urls just to the main page


Super new to varnish. As the title states. I want to redirect anything under example.com/* to just https://example.com/

so far I've tried

if (client.ip != "127.0.0.1" && req.http.host == "example.com") {
        set req.http.x-redir = "https://example.com";
        error 850 "Moved Permanently";
      }

Any thoughts on how I can do this?


Solution

  • Have a look at this specific section of a tutorial I wrote: https://www.varnish-software.com/developers/tutorials/redirect/#http-to-https-redirections.

    Here's the code I would use for that:

    vcl 4.1;
    
    import proxy;
    
    backend default {
        .host = "127.0.0.1";
        .port = 8080;
    }
    
    sub vcl_recv {
        if ((req.http.X-Forwarded-Proto && req.http.X-Forwarded-Proto != "https") || 
            (req.http.Scheme && req.http.Scheme != "https")) {
            return (synth(750));
        } elseif (!req.http.X-Forwarded-Proto && !req.http.Scheme && !proxy.is_ssl()) {
            return (synth(750));
        }
    }
    
    sub vcl_synth {
        if (resp.status == 750) {
            set resp.status = 301;
            set resp.http.location = "https://" + req.http.Host + req.url;
            set resp.reason = "Moved";
            return (deliver);
        }
    }
    
    

    This tutorial checks 3 things:

    • Whether or not the URL scheme of the request is sent via the X-Forwarded-Proto header
    • Whether or not the URL scheme of the request is sent via the X-Scheme header which is part of HTTP/2
    • Whether or not the PROXY protocol was used and the PROXY TLV attributes contains the scheme

    When either of these checks concludes that plain HTTP is used, the return(synth(750)) return statement is used to return a synthetic response.

    In the vcl_synth subroutine, status code 750 is caught and results in a 301 redirect to the HTTPS version of that request.

    The X-Forwarded-Proto header should be set by your TLS PROXY if you're connecting to Varnish using regular HTTP.

    If instead you're using the PROXY protocol to connect to Varnish, you should have a look at the following tutorial: https://www.varnish-software.com/developers/tutorials/proxy-protocol-varnish/