Tuesday, January 15, 2013

Wordpress & Varnish



Basic configuration, tiny bit of security and avoiding error 405 on post. This server runs other things as well, so configurations are not as aggressive as they might be in other places.

backend default {
.host = "127.0.0.1";
.port = "8080";
}

acl purge {
        "localhost";
}

sub vcl_recv {

    /* Before anything else we need to fix gzip compression */
    if (req.http.Accept-Encoding) {
        if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|mp4)$") {
            # No point in compressing these
            remove req.http.Accept-Encoding;
        } else if (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
        } else if (req.http.Accept-Encoding ~ "deflate") {
            set req.http.Accept-Encoding = "deflate";
        } else {
            # unknown algorithm
            remove req.http.Accept-Encoding;
        }
    }
    # Login, administration and posting comments are to be completely and utterly left alone, no caching, no nothing.
    if (req.http.host == "my.blog.com") {
        if (req.url ~ "wp-(login|admin|comments-post)") {
                set req.backend = default;
            return(pipe);
        }
        # Drop any cookies sent to Wordpress.
    unset req.http.cookie;
        if (req.request == "PURGE") {
                if (!client.ip ~ purge) {
                        error 405 "Not allowed.";
                }
        }
        set req.backend = default;
        return (lookup);
    }
     if (req.url ~ "\.(jpeg|jpg|png|gif|ico|swf|js|css|txt|gz|zip|rar|bz2|tgz|tbz|html|htm|pdf|mp4)$") {
         unset req.http.cookie;
     set req.grace = 5m;
         return(lookup);
     }
     return(pass);
}

sub vcl_fetch {
    if (beresp.status == 302) {
        set beresp.http.X-Magic-Redirect = "1";
        return(deliver);
    }
    if (req.url ~ "\.(jpeg|jpg|png|gif|ico|swf|js|css|txt|gz|zip|rar|bz2|tgz|tbz|html|htm|pdf|mp4)$") {
        unset beresp.http.set-cookie;
    }
    set beresp.do_stream = true;
    if (req.http.Authorization) {
        return (hit_for_pass);
    }
}

sub vcl_hit {
    if (obj.http.X-Magic-Redirect == "1") {
        set req.url = obj.http.Location;
        return (restart);
    }

    if (req.request == "PURGE") {
        set obj.ttl = 0s;
        error 200 "Purged.";
    }

}
sub vcl_deliver {
    if (resp.http.X-Magic-Redirect == "1") {
        unset resp.http.X-Magic-Redirect;
        return(restart);
    }
    return(deliver);
}

No comments:

Post a Comment