Skip to content

Instantly share code, notes, and snippets.

@gerrgg
Last active August 5, 2020 15:07
Show Gist options
  • Save gerrgg/16c48f3cdde463076d1aed295e2550f0 to your computer and use it in GitHub Desktop.
Save gerrgg/16c48f3cdde463076d1aed295e2550f0 to your computer and use it in GitHub Desktop.
<IfModule mod_setenvif.c>
# Vary: Accept for all the requests to jpeg and png
SetEnvIf Request_URI "\.(jpe?g|png)$" REQUEST_image
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
# Check if browser supports WebP images
RewriteCond %{HTTP_ACCEPT} image/webp
# Check if WebP replacement image exists
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
# Serve WebP image instead
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp]
</IfModule>
<IfModule mod_headers.c>
Header append Vary Accept env=REQUEST_image
</IfModule>
<IfModule mod_mime.c>
AddType image/webp .webp
</IfModule>
#!/bin/bash
# converting JPEG images
find $1 -type f -and \( -iname "*.jpg" -o -iname "*.jpeg" \) \
-exec bash -c '
webp_path=$(sed 's/\.[^.]*$/.webp/' <<< "$0");
if [ ! -f "$webp_path" ]; then
cwebp -q 90 "$0" -o "$webp_path";
fi;' {} \;
# converting PNG images
find $1 -type f -and -iname "*.png" \
-exec bash -c '
webp_path=$(sed 's/\.[^.]*$/.webp/' <<< "$0");
if [ ! -f "$webp_path" ]; then
cwebp -lossless "$0" -o "$webp_path";
fi;' {} \;
# USAGE - towebp.sh ~/path/to/your/media/folder
@gerrgg
Copy link
Author

gerrgg commented Aug 5, 2020

I wrote this to convert entire directories of .jpg and .png files into .webp - making your website fast and beautiful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment