Skip to content

Instantly share code, notes, and snippets.

@marcus-downing
Forked from anonymous/gist:eb271011b40a107619ae
Last active August 29, 2015 14:12
Show Gist options
  • Save marcus-downing/19d16e93754733393326 to your computer and use it in GitHub Desktop.
Save marcus-downing/19d16e93754733393326 to your computer and use it in GitHub Desktop.
check_http_cache
#!/bin/sh
# Check HTTP cache
# Nagios test to check if a website has the correct cache control headers
ADDRESS="$1"
# Make two requests, capture the response headers on the second so we can see if it was delivered from the cache
curl -s "http://$ADDRESS/" -o /dev/null
HEADERS="$(curl -s -D - "http://$ADDRESS/" -o /dev/null)"
# If the page was actually delivered by a cache, that's proof it worked
if X_CACHE="$(echo "$HEADERS" | grep '^X-Cache:')"; then
if X_CACHE_HIT="$(echo "$X_CACHE" | grep 'HIT')"; then
echo "$X_CACHE_HIT"
return 0
fi
fi
# Look for bypass directives
if CACHE_CONTROL="$(echo "$HEADERS" | grep -e '^Cache-Control:')"; then
if CACHE_CONTROL_NO_CACHE="$(echo "$CACHE_CONTROL" | grep 'no-cache')"; then
echo "$CACHE_CONTROL_NO_CACHE"
return 2
fi
fi
if PRAGMA="$(echo "$HEADERS" | grep -e '^Pragma:')"; then
if PRAGMA_NO_CACHE="$(echo "$PRAGMA" | grep 'no-cache')"; then
echo "$PRAGMA_NO_CACHE"
return 2
fi
fi
# If the expires header is in the future, it should be cachable
if EXPIRES="$(echo "$HEADERS" | grep -e '^Expires:')"; then
EXPIRES_DATE="$(echo "$EXPIRES" | head -n 1 | sed 's/^Expires://' | sed 's/\r$//')"
TIME_NOW="$(date +'%s')"
TIME_EXPIRES="$(date -d "$EXPIRES_DATE" +'%s')"
if [ "$TIME_NOW" -lt "$TIME_EXPIRES" ]; then
echo "$EXPIRES"
return 0
fi
fi
# An ETag header isn't really right, but it downgrades from critical to warning
if ETAG="$(echo "$HEADERS" | grep -e '^ETag:')"; then
echo "$ETAG"
return 1
fi
echo "No cache control headers found"
echo ""
echo "$HEADERS"
return 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment