Skip to content

Instantly share code, notes, and snippets.

@fbatschi
Last active January 2, 2020 05:12
Show Gist options
  • Save fbatschi/7a8fbf981f17977a48965f9262d29541 to your computer and use it in GitHub Desktop.
Save fbatschi/7a8fbf981f17977a48965f9262d29541 to your computer and use it in GitHub Desktop.
Nginx fastcgi/proxy Cache Manager
#!/bin/bash
# search and optionally purge cached content from nginx by URL or parts of the URL
# you can set the default cache dir
DEFAULT_NGINX_CACHE_DIR=/dev/shm/nginx
function usage {
echo "nginx cache - search and purge content from nginx"
echo ""
echo "Searches for a 'query' in the Nginx cache key set by proxy_cache_key,"
echo "which is most likely defined as the url of the cached content"
echo "Hint: proxy_cache_key might be set including port number (host:port)"
echo ""
echo "Usage:"
echo " $0 [flags] <query> [cachedir]"
echo ""
echo "Flags:"
echo " -d purge content when query matches"
echo ""
echo "Arguments:"
echo " query string to search in nginx cache key"
echo " cachedir path to nginx cache dir. (default: $DEFAULT_NGINX_CACHE_DIR)"
}
DELETE=0
# parse flags
OPTIND=1
while getopts "dh" options; do
case $options in
d ) DELETE=1 ;;
h ) usage ;;
* ) usage ;;
esac
done
shift $((OPTIND-1))
QUERY=$1
CACHEDIR=${2:-$DEFAULT_NGINX_CACHE_DIR}
if [ -z ${QUERY} ]; then
echo -e "Error: No query given\n"
usage
exit
fi
if [ ! -d "${CACHEDIR}" ]; then
echo -e "Error: Nginx Cache Dir does not exist\n"
usage
exit
fi
# now search
echo -e "Searching for query \033[1m${QUERY}\033[0m\n"
# grep matches
MATCHES=`grep --text -r "KEY:" ${CACHEDIR} | grep ${QUERY}`
MATCHES_FILES=`echo "$MATCHES" |cut -d ":" -f1 `
if [ -z "${MATCHES}" ]; then
echo "No matches found"
MATCH_COUNT=0
else
MATCH_COUNT=`echo "${MATCHES}" | wc -l`
echo -e "Found ${MATCH_COUNT} match(es) in ${CACHEDIR}:"
echo "$MATCHES"
# if delete option has been set, remove content from cache
# by deleting the cached file from disk
if [ ${DELETE} = 1 ]; then
echo Purging content
echo "${MATCHES_FILES}" | xargs rm
echo Done
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment