diego-treitos / nginx_cache_multipurge

31 stars 12 forks source link

Nginx Cache Multipurge (lua)

Description

Handle cache purges in a versatile and easy way. This lua module will allow you to request the removal from cache of one or multiple urls using a wild card * at the end.

Requirements

Installation

Configuration

Available Configuration Variables

Example 1: Mimic the commercial cache_purge

Add this map somewhere (i.e. /etc/nginx/conf.d/method_map.conf)

map $request_method $cmp_run_if {
    default 0;
    PURGE 1;
}

Then, in a location

location / {
  proxy_pass http://backend;
  proxy_cache my-awesome-cache;
  proxy_cache_key $scheme$host$uri$is_args$args;

  # NOTE: We already defined $cmp_run_if in the map
  set $cmp_cache_key $scheme$host$uri$is_args$args;
  set $cmp_cache_path "/var/www/cache";
  content_by_lua_file /etc/nginx/lua/cache_multipurge.lua;
}

And done. After this:

Example 2: Use a custom location with a authentication token from a cookie

Add a map like this, for example in /etc/nginx/conf.d/cache_purge.conf

map $cookie_purge_token $purge_cache {
  default 0;
  b04f01fc92094bcc43d1cb78adc7836e 1;
}

Then add a location like this

location /cache/purge {
  set $cmp_run_if $purge_cache;
  set $cmp_cache_key $scheme$host$uri$is_args$args;
  set $cmp_cache_path "/var/www/cache/";
  set $cmp_cache_strip "/cache/purge/";
  content_by_lua_file /etc/nginx/lua/cache_multipurge.lua;
}

And done. After this:

Optional keyfinder helper setup

If your cache consists of a large number of files, scanning it with grep can become quite slow. To gain better performance, you can use the included keyfinder helper. You’ll have to build it yourself, however.

Requirements

You will need gcc, libc headers and make. On Debian/Ubuntu type (libc is included with gcc):

apt install gcc make

Installation

Build the binary with

make

and then install as root with

make install

By default the nginx_cache_keyfinder binary is installed in /usr/local/bin. If you want a different location, you can copy it manually instead.

Configuration

Enable the keyfinder in your purge location config:

set $cmp_cache_keyfinder 1;

If you choose to put the binary in a different location, you can adjust its path with

set $cmp_cache_keyfinder_path <path to binary>;