Skip to content

Instantly share code, notes, and snippets.

@mitchellkrogza
Created August 16, 2021 12:07
Show Gist options
  • Save mitchellkrogza/d768ce119cdf8273cf40a2990e9ce563 to your computer and use it in GitHub Desktop.
Save mitchellkrogza/d768ce119cdf8273cf40a2990e9ce563 to your computer and use it in GitHub Desktop.
Generate webp images from png and jpg files recursively in any web folder (uses webp command line tool)
#!/bin/bash
# ---------------------------------------------------------------------------
# Generate WebP Images - Uses cwebp command line tool for Linux
# This will generate / re-generate all webp images for all JPG and PNG files
# Being command line based it is incredibly fast
# If you don't want to re-generate existing files set generateall=0
# If you want to re-generate everything set generateall=1
# USE this script at your own risk and Only if you know what you are doing
# Written by Mitchell Krog - [email protected]
# https://github.com/mitchellkrogza
# ---------------------------------------------------------------------------
# -------- #
# SETTINGS #
# -------- #
generateall=0 # <--- Set to 1 to re-generate all webp files / 0 will only generate missing webp files
mydomain="mydomain.com" # <--- Enter your domain / folder name here
directory="/srv/http/${mydomain}/wp-content/uploads/" # <--- Some servers use /var/www change if necessary - Change folder structure as needed
quality=80
# ------------ #
# END SETTINGS #
# ------------ #
if [[ "${generateall}" == 1 ]]
then
for file in $(find ${directory} -type f \( -name "*.jpg" -o -name "*.png" \))
do
echo "converting ${file}"
cwebp -q ${quality} -lossless ${file} -o "${file%.*}.webp"
done
else
for file in $(find ${directory} -type f \( -name "*.jpg" -o -name "*.png" \))
do
if test -f "${file%.*}.webp"
then
echo "file exists - skipping"
else
echo "convert ${file}"
cwebp -q ${quality} -lossless ${file} -o "${file%.*}.webp"
fi
done
fi
exit 0
@mitchellkrogza
Copy link
Author

mitchellkrogza commented Oct 13, 2021

Hi @andyg2 it can be done through an .htaccess rewrite or an Nginx rule but I would recommend against it as any non webp compliant browsers would not be able to see any images on the site. The proper way it to use a vary method of serving the images

For apache / htaccess

<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteCond %{HTTP_ACCEPT} image/webp
	RewriteCond %{REQUEST_FILENAME} (.*)\.(jpe?g|png|gif)$
	RewriteCond %{REQUEST_FILENAME}\.webp -f
	RewriteCond %{QUERY_STRING} !type=original
	RewriteRule (.+)\.(jpe?g|png|gif)$ %{REQUEST_URI}.webp [T=image/webp,L]
</IfModule>
<IfModule mod_headers.c>
	<FilesMatch "\.(jpe?g|png|gif)$">
		Header append Vary Accept
	</FilesMatch>
</IfModule>
AddType image/webp .webp

for Nginx

# WebP rules
# --------------------
location ~* ^.+\.(png|jpe?g)$ {
  add_header Vary Accept;
  	expires 365d;
    access_log off;
    add_header Cache-Control "max-age=31536000, public";
  if ($http_accept !~* "webp"){
    break;
  }
  # Server webp or fallback to jpeg
  try_files $uri$webp_suffix $uri =404;
  }
# ------------------- (WebP rules ends here)

@andyg2
Copy link

andyg2 commented Oct 13, 2021

Hi @andyg2 it can be done through an .htaccess rewrite or an Nginx rule. The proper way it to use a vary method of serving the images.

Ooh, I'd never head of Vary Accept, I'll be using this for sure, thanks!

@mitchellkrogza
Copy link
Author

Hi @andyg2 it can be done through an .htaccess rewrite or an Nginx rule. The proper way it to use a vary method of serving the images.

Ooh, I'd never head of Vary Accept, I'll be using this for sure, thanks!

This is essentially what plugins do for you but you only need this short bit of code at server level and no plugins are required to serve webp to appropriate devices.

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