Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Last active February 16, 2017 23:28
Show Gist options
  • Save tzkmx/e13dc1c76729ebdd9408c67ba6817e61 to your computer and use it in GitHub Desktop.
Save tzkmx/e13dc1c76729ebdd9408c67ba6817e61 to your computer and use it in GitHub Desktop.
Custom Perl Module for NginX in order to remove single URIs cached

Custom module to purge cached URIs

Let's suppose you have this fastcgi_cache config:

fastcgi_cache_path /var/run/nginx-cache levels=2:2 keys_zone=WORDPRESS:2048m inactive=120m;

By using this module, in order to purge a single cached uri you can use a query like:

curl localhost/invalid_cache/mydomain.com/my_uri

I'd recommend allowing access to this path for invalidating the cache, only from localhost:

    location /invalid_cache {
        allow 127.0.0.1;
        deny all;
        set $prefix '/invalid_cache/';
        perl purge_cache::handler;
    }

In order to make use of this module, you should put it in your modules path and require it:

    perl_modules /etc/nginx/perl/lib;
    perl_require purge_cache.pm;
package purge_cache;
use nginx;
use Digest::MD5;
sub handler {
my $r = shift;
my $uri = $r->uri;
my $prefix = $r->variable('prefix');
my $replace = 'GET';
my $cache_path = '/var/run/nginx-cache';
$uri =~ s/$prefix/$replace/;
my $ctx = Digest::MD5->new;
$ctx->add($uri);
my $hex = $ctx->hexdigest;
my $path = sprintf "%s/%s/%s/%s", $cache_path, (substr $hex, -2), (substr $hex, -4, 2), $hex;
$r->send_http_header;
$r->print($uri, "\n", $path, "\t");
if(-e $path) {
unless( unlink $path ) { $r->print('not removed', "\n"); }
} else {
$r->print('not found', "\n");
}
return OK;
}
1;
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment