Skip to content

Instantly share code, notes, and snippets.

@samba
Created June 15, 2012 18:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samba/2938014 to your computer and use it in GitHub Desktop.
Save samba/2938014 to your computer and use it in GitHub Desktop.
Nginx Cache Search/Removal
#!/bin/sh
# Nginx Cache Manager (search, remove content by URL or grep)
# NOTE:
# in my nginx config, I use:
# proxy_cache_key $scheme://$host$uri$is_args$args@$remote_user;
# ... which facilitates easier searching of cache files
cachefiles () {
find /var/lib/nginx/cache -type f $@
}
# Apply proper regexp wildcards if the search isn't anchored
expando () {
local OPTARG="$@";
[ -z "${OPTARG##^*}" ] || OPTARG="(.*)${OPTARG}"
[ -z "${OPTARG%%*$}" ] || OPTARG="${OPTARG}(.*)"
echo "$OPTARG"
}
ALLTEXT='--binary-files=text'
filterfiles () {
listonly='' nullsep=''
while getopts :t:k:C:l0- OPT; do
case $OPT in
0) nullsep='-0';;
l) listonly='-l';;
t) xargs $nullsep grep $ALLTEXT $listonly -E "^Content-Type:\s+`expando ${OPTARG}`";;
k) xargs $nullsep grep $ALLTEXT $listonly -E "^KEY:\s+`expando ${OPTARG}`";;
C) xargs $nullsep grep $ALLTEXT $listonly "${OPTARG}";;
-) break;;
esac
done
}
usage () {
cat <<EOF
Usage: $0 <verb> <options>
Examples:
$0 flush delete all files from the cache
$0 list [findopts] list files in the cache (options go to 'find')
$0 search -l -t 'text/css' list all files with Content-Type: text/css
$0 search -l -k '/site/core.js@' list all files from URLs ending in '/site/core.js'
$0 search -l -k 'blah' list all files with URLs containing 'blah'
$0 search -l -C "grep-pattern" list all files matching pattern as found by grep
$0 remove <options like search>
Note:
-l on search lists files. Leaving it off shows content.
EOF
}
mode=$1; shift;
case $mode in
-h|help) usage;;
flush) cachefiles -delete;;
list) cachefiles "$@";; # Pass arguments directly to find
search) cachefiles -print0 | filterfiles -0 "$@";;
remove) cachefiles -print0 | filterfiles -0 -l "$@" | xargs -n rm -v;;
filter) filterfiles "$@";; # allow the filter to be called externally
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment