Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save locvfx/d933ca5d07efaf5c1d44e3dc73553a8c to your computer and use it in GitHub Desktop.

Select an option

Save locvfx/d933ca5d07efaf5c1d44e3dc73553a8c to your computer and use it in GitHub Desktop.
Recursively pre-compress (gzip) CSS/JavaScript/webfont assets for use Nginx and its HttpGzipStaticModule module.
#!/bin/bash -e
function compressResource {
gzip --best "$1" >"$1.gz"
touch --no-create --reference="$1" "$1.gz"
echo "Compressed: $1 > $1.gz"
}
# fetch list of websites
IFS=$'\n'
for appDir in $(find /var/www/* -maxdepth 0)
do
# fetch all existing gzipped CSS/JavaScript/webfont files and remove files that do not have a base uncompressed file
for compressFile in $(find "$appDir" -type f \( -name "*.css.gz" -or -name "*.js.gz" -or -name "*.eot.gz" -or -name "*.svg.gz" -or -name "*.ttf.gz" \))
do
if [[ ! -f ${compressFile%.gz} ]]; then
# remove orphan gzipped file
rm "$compressFile"
echo "Removed: $compressFile"
fi
done
# fetch all source CSS/JS/webfont files - excluding *.src.* variants (pre-minified CSS/JavaScript)
# gzip each file and give timestamp identical to that of the uncompressed source file
for sourceFile in $(find "$appDir" -type f \( -name "*.css" -or -name "*.js" -or -name "*.eot" -or -name "*.svg" -or -name "*.ttf" \) \( ! -name "*.src.css" -and ! -name "*.src.js" \))
do
if [[ -f "$sourceFile.gz" ]]; then
# only re-gzip if source file is different in timestamp to the existing gzip file
if [[ ($sourceFile -nt "$sourceFile.gz") || ($sourceFile -ot "$sourceFile.gz") ]]; then
compressResource "$sourceFile"
fi
else
compressResource "$sourceFile"
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment