Clearing Nginx Cache Programmatically with Webbooks (GhostCMS)

Extending the functionality of a standard NGINX installation on a Debian system, we can utilize the "Webhook" package to execute local scripts

Clearing Nginx Cache Programmatically with Webbooks (GhostCMS)
Photo by Shannon Potter / Unsplash

NGINX offers powerful caching capabilities, but when using the open-source version without additional modules or OpenResty, clearing the cache when content changes can be challenging. However, many content management systems (CMS), such as Ghost, provide webhooks that send POST requests when specific events occur. To extend the functionality of a standard NGINX installation on a Debian system, we can utilize the "Webhook" package to execute local scripts. This approach offers a straightforward method to clear the NGINX cache in response to content updates, making it an efficient solution for managing dynamic content delivery.

We can start off with install the webhook package using APT

sudo apt update
sudo apt install webhook

Next, we can write out a script that clears our NGINX cache directory, you can change this to fit your needs if you have your specific site cache in other locations. We can run nano clear_nginx_cache.sh and enter the following:

#!/bin/bash

# Define the cache directory
CACHE_DIR="/var/cache/nginx/"

# Function to handle errors
handle_error() {
    echo "An error occurred on line $1"
    exit 1
}

# Trap errors
trap 'handle_error $LINENO' ERR

# Remove all cached files
rm -rf "${CACHE_DIR}"/* || true

# Reload nginx
nginx -s reload || { echo "Failed to reload Nginx"; exit 1; }

echo "Nginx cache cleared."

Remember to make your script executable with chmod +x clear_nginx_cache.sh

Now let's configure the webhook package. By default it looks for a config file, but instead we're going to feed it our JSON with webhooks configured. We write a new file called hooks.json here we set the script we want to run, and it's location. The ID that is used will be the used in the URL of the webhook. In this case I'm using the nginx directory but suggest you change it to suit your workflow.

[
  {
    "id": "clear-cache-webhook",
    "execute-command": "/etc/nginx/clear_nginx_cache.sh",
    "command-working-directory": "/etc/nginx"
  },
]

Then we can set the webhook package to use the correct configuration file. So we will run sudo nano /lib/systemd/system/webhook.service

webhook.service

We can comment out the line ConditionPathExists=/etc/webhook.conf with a # or remove it completely. And change the execution line to match the location of out hooks.json file ExecStart=/usr/bin/webhook -nopanic -hooks /etc/nginx/hooks.json

After we save out changes we need to restart the webhook service with systemctl restart webhook.service

Now, we are set to use the webhook with a POST request to http://yourserver:9000/hooks/clear-cache-webhook