WordPress webp images
WebP is a modern image format that provides excellent compression without loss of image on the web.
In this post I will share how to make our wordpress blog work with this format for better optimization with the help of nginx and webp.
Install webp
apt-get install webp
webp is needed by our script, which will convert all the images jpg/png in webp.
Webp script
The script looks like this:
#!/bin/bash # Depends on cwebp # 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 -quiet -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 -quiet -lossless "$0" -o "$webp_path"; fi;' {} \;
We put it on cron and makes it runs once every day. Runs like this :
/root/webp.sh /var/www/saitani.com
Webp mime type
In /etc/nginx/mime.types add :
image/webp webp;
and restart nginx.
Nginx vhost
Vhost nginx configuration is:
We add map block on the top:
map $sent_http_content_type $expires { default off; text/html epoch; text/css max; application/javascript max; ~image/ max; } map $http_accept $webp_suffix { default ""; "~*webp" ".webp"; }
And below we add the following two blocks that deal with png / jpg extensions:
location ~* ^(/wp-content/.+)\.(png|jpg)$ { add_header Vary "Accept-Encoding"; add_header Cache-Control "public, no-transform"; try_files $uri$webp_suffix $uri =404; } location ~* ^(/.+)\.(png|jpg)$ { add_header Vary "Accept-Encoding"; add_header Cache-Control "public, no-transform"; try_files $uri$webp_suffix $uri =404; }
The idea is ; if our browser supports webp nginx will serve the images in webp format.
If not, will serve the images in their original format – png or jpg.
Testing
Open Developer -> Developer Tools on google chrome, go to Network and refresh the site. If everything is ok, in the field type should see all of our images in webp format.
So this is all about WordPress webp images
10x namesake!