WebP Express

Descripción

Más de 9 de cada 10 usuarios utilizan un navegador capaz de mostrar imágenes webp. Sin embargo, en la mayoría de los sitios web se les ofrecen imágenes jpeg, que suelen duplicar el tamaño de las imágenes webp para una calidad dada. ¡Qué desperdicio de ancho de banda! Este plugin fue creado para ayudar a remediar esta situación. Con poco esfuerzo, los administradores de WordPress pueden hacer que su sitio sirva imágenes webp autogeneradas a los navegadores que lo soportan, mientras que siguen sirviendo archivos jpeg y png a los navegadores que no soportan webp.

El convertidor de imágenes

El plugin utiliza la biblioteca WebP Convert para convertir imágenes a webp. WebP Convert puede convertir imágenes utilizando varios métodos. Existen los métodos de conversión «locales»: imagick, cwebp, vips, gd. Si ninguno de ellos funciona en tu servidor, existen alternativas en la nube: ewww (de pago) o conectando a un sitio de WordPress donde tienes instalado WebP Express y habilitaste la funcionalidad «servicio web».

La parte «Sirviendo webp a los navegadores compatibles».

The plugin supports different ways of delivering webps to browsers that supports it:

  1. By routing jpeg/png images to the corresponding webp – or to the image converter if the image hasn’t been converted yet.
  2. By altering the HTML, replacing image tags with picture tags. Missing webps are auto generated upon visit.
  3. By altering the HTML, replacing image URLs so all points to webp. The replacements only being made for browsers that supports webp. Again, missing webps are auto generated upon visit.
  4. In combination with Cache Enabler, the same as above can be achieved, but with page caching.
  5. You can also deliver webp to all browsers and add the webpjs javascript, which provides webp support for browsers that doesn’t support webp natively. However, beware that the javascript doesn’t support srcset attributes, which is why I haven’t added that method to the plugin (yet).

The plugin implements the «WebP On Demand» solution described here and builds on a bunch of open source libraries (all maintained by me):
WebP Convert: For converting images to webp
WebP Convert Cloud Service: For the Web Service functionality
DOM Util for WebP: For the Alter HTML functionality
Image MimeType Guesser: For detecting mime types of images.
HTAccess Capability Tester: For testing .htaccess capabilities in a given directory, using live tests
WebP Convert File Manager: For browsing conversions and triggering conversions.
Exec With Fallback: For emulating exec() on systems where it is disabled (using proc_open(), passthru() or similar alternatives).

Benefits

  • Much faster load time for images in browsers that supports webp. The converted images are typically less than half the size (for jpeg), while maintaining the same quality. Bear in mind that for most web sites, images are responsible for the largest part of the waiting time.
  • Better user experience (whether performance goes from terrible to bad, or from good to impressive, it is a benefit).
  • Better ranking in Google searches (performance is taken into account by Google).
  • Less bandwidth consumption – makes a huge difference in the parts of the world where the internet is slow and costly (you know, ~80% of the world population lives under these circumstances).
  • Actualmente, el ~97% de todo el tráfico se realiza con navegadores compatibles con webp.
  • It’s great for the environment too! Reducing network traffic reduces electricity consumption which reduces CO2 emissions.

Limitations

Supporting WebP Express

Bread on the table don’t come for free, even though this plugin does, and always will. I enjoy developing this, and supporting you guys, but I kind of need the bread too. Please make it possible for me to continue wasting time on this plugin:

Supporters of WebP Express

Personas que han contribuido recientemente con ko-fi – ¡Gracias!

  • 3 Nov: Tobi
  • 5 Nov: Anon
  • 18 Nov: Oleksii
  • 20 Feb: Assen Kovatchev
  • 22 Feb: Peter
  • 29 Feb: Luis Méndez Alejo
  • 5 Mar: tomottoe
  • 9 Mar: La Braud

Persons who contributed with extra generously amounts of coffee / lifetime backing (>30$) – thanks!:

  • Max Kreminsky ($115)
  • Justin – BigScoots ($105)
  • Bill Vallance ($102)
  • Label Vier ($100)
  • Sebastian ($99)
  • Tammy Lee ($90)
  • Steven Sullivan ($51)
  • Mathieu Gollain-Dupont ($50)
  • Erica Dreisbach ($50)
  • Brian Laursen ($50)
  • Dimitris Vayenas ($50)

Personas que actualmente respaldan el proyecto a través de GitHub Sponsors o Patreon – ¡Gracias!

Capturas

  • WebP Express settings

Instalación

  1. Upload the plugin files to the /wp-content/plugins/webp-express directory, or install the plugin through the WordPress plugins screen directly.
  2. Activate the plugin through the ‘Plugins’ screen in WordPress
  3. Configure it (the plugin doesn’t do anything until configured)
  4. Verify that it works
  5. (Opcional) Convertir en lote todas las imágenes, ya sea en la interfaz de administración o utilizando WP CLI (comando: «webp-express»)

Configurando

You configure the plugin in Settings > WebP Express.

Operation modes

As sort of a main switch, you can choose between the following modes of operation:

Varied image responses:
WebP Express creates redirection rules for images, such that a request for a jpeg will result in a webp – but only if the request comes from a webp-enabled browser. If a webp already exists, it is served immediately. Otherwise it is converted and then served. Note that not all CDN’s handles varied responses well.

CDN friendly:
In «CDN friendly» mode, a jpeg is always served as a jpeg. Instead of varying the image response, WebP Express alters the HTML for webp usage.

Just redirect:
In «just redirect» mode, WebP Express is used just for redirecting jpeg and pngs to existing webp images in the same folder. So in this mode, WebP express will not do any converting. It may be that you use another plugin for that, or that you converted the images off-line and uploaded them manually.

Tweaked:
Here you have all options available.

Conversion methods

WebP Express has a bunch of methods available for converting images: Executing cwebp binary, Gd extension, Imagick extension, ewww cloud converter and remote WebP express. Each requires something. In many cases, one of the conversion methods will be available. You can quickly identify which converters are working – there is a green icon next to them. Hovering conversion methods that are not working will show you what is wrong.

In case no conversion methods are working out of the box, you have several options:
– You can install this plugin on another website, which supports a local conversion method and connect to that using the «Remote WebP Express» conversion method
– You can purchase a key for the ewww cloud converter. They do not charge credits for webp conversions, so all you ever have to pay is the one dollar start-up fee 🙂
– You can set up webp-convert-cloud-service on another server and connect to that. Its open source.
– You can try to meet the server requirements of cwebp, gd, imagick or gmagick. Check out this wiki page on how to do that

Quality detection of jpegs

If your server has Imagick extension or is able to execute imagemagick binary, the plugin will be able to detect the quality of a jpeg, and use that quality for the converted webp. You can tell if the quality detection is available by hovering the help icon in Conversion > Jpeg options > Quality for lossy. The last line in that help text tells you.

This auto quality has benefits over fixed quality as it ensures that each conversion are converted with an appropriate quality. Encoding low quality jpegs to high quality webps does not magically increase the visual quality so that your webp looks better than the original. But it does result in a much larger filesize than if the jpeg where converting to a webp with the same quality setting as the original.

If you do not have quality detection working, you can try one of the following:
– Install Imagick on the server (for this purpose, it is not required that it is compiled with WebP support)
– Install imagemagick on the server and grant permission for PHP to use the «exec» function.
– Use «Remote WebP Express» converter to connect to a site, that does have quality detection working
– If you have cwebp converter available, you can configure it to aim for a certain reduction, rather than using the quality parameter. Set this to for example 50%, or even 45%.

Verifying that it works (in «Varied image responses» mode)

  1. Asegúrate de que al menos uno de los métodos de conversión funciona. Deberías tener una marca de verificación verde al lado.
  2. Si aún no has guardado, haz clic en «Guardar ajustes». Esto colocará las reglas de redirección en archivos .htaccess en los directorios relevantes (generalmente en uploads, themes y wp-content/webp-express/webp-images, según la configuración).
  3. Supongo que has marcado al menos una de las dos primeras casillas de verificación en la sección de reglas .htaccess. De lo contrario, no estarás utilizando «respuestas variadas» y, en ese caso, el modo «Amigable con CDN» sería más apropiado.
  4. Haz clic en los botones «Prueba en vivo» para verificar que las reglas activadas estén realmente funcionando. Si no lo están, podría ser que el servidor necesite un poco de tiempo para reconocer las reglas cambiadas.

Las pruebas en vivo son bastante exhaustivas y las recomiendo por encima de una prueba manual. Sin embargo, no está de más hacer también una inspección manual.

Realizar una inspección manual

Ten en cuenta que cuando WebP Express está sirviendo respuestas de imagen variadas, las URL de las imágenes siguen apuntando al jpg/png. Sin embargo, si se visita la URL utilizando un navegador que admite webp, la respuesta será una imagen webp. Por lo tanto, hay una discrepancia entre la extensión del archivo (el nombre de archivo termina en «jpg» o «png») y el tipo de archivo. Pero afortunadamente, el navegador no se basa en la extensión para determinar el tipo de archivo, solo examina la cabecera de respuesta Content-Type.

Para comprobar que el plugin funciona (sin hacer clic en el botón de prueba), haz lo siguiente:

  • Abre la página en un navegador que admita webp, por ejemplo Google Chrome
  • Right-click the page and choose «Inspect»
  • Click the «Network» tab
  • Reload the page
  • Find a jpeg or png image in the list. In the «type» column, it should say «webp»

También puedes revisar las cabeceras. Cuando WebP Express haya redirigido a un archivo webp existente, habrá una cabecera «X-WebP-Express» con el siguiente valor: «Redirigido directamente a webp existente». Si no está presente (y has activado «Habilitar redirección al convertidor»), deberías ver una cabecera «WebP-Convert-Log» (WebP-Express utiliza el convertidor WebP para las conversiones).

Notes

Note:
The redirect rules created in .htaccess are pointing to a PHP script. If you happen to change the url path of your plugins, the rules will have to be updated. The .htaccess also passes the path to wp-content (relative to document root) to the script, so the script knows where to find its configuration and where to store converted images. So again, if you move the wp-content folder, or perhaps moves WordPress to a subfolder, the rules will have to be updated. As moving these things around is a rare situation, WebP Express are not using any resources monitoring this. However, it will do the check when you visit the settings page.

Note:
Do not simply remove the plugin without deactivating it first. Deactivation takes care of removing the rules in the .htaccess file. With the rules there, but converter gone, your Google Chrome visitors will not see any jpeg images.

Conversión en lotes

Puedes iniciar una conversión masiva de dos formas:
1. En la interfaz de administración. En la pantalla de configuración, hay un botón «Conversión en lotes».
2. Usando WP CLI (comando: «webp-express»).

Actualmente, estoy trabajando en una interfaz de gestor de archivos, que se convertirá en una tercera vía.

Asegurándose de que las nuevas imágenes se convierten

Hay varias formas:
1. Habilitar la redirección a conversor en la sección de reglas .htaccess.
2. Activar «Convertir al subir». Ten en cuenta que esto puede afectar a la experiencia de carga en temas que definen muchos formatos.
3. Configura una tarea cron, que ejecute wp webp-express convert regularmente.

Comando WP CLI

WebP Express actualmente soporta comandos para convertir y descargar imágenes webp a través de la CLI. Puede utilizar la opción –help para conocer las opciones:
wp webp-express –help. Muestra los comandos disponibles
wp webp-express convert –help. Muestra las opciones disponibles para el comando «convert».

Algunos ejemplos:
wp webp-express convert: Crea imágenes webp para todas las imágenes no convertidas
wp webp-express convert –reconvert: También convierte imágenes que ya están convertidas
wp webp-express convert themes: Solo imágenes en la carpeta de temas
wp webp-express convert uploads/2021: Solo imágenes en la carpeta «2021» dentro de la carpeta de subidas
wp webp-express convert –only-png: Solo las imágenes PNG
wp webp-express convert –quality=50: Usa calidad 50 (en lugar de lo que se ingresó en la pantalla de ajustes)
wp webp-express convert –converter=cwebp: Usa específicamente el convertidor cwebp.

wp webp-express flushwebp: Eliminar todas las imágenes webp
wp webp-express flushwebp –only-png: Elimina todas las imágenes webp que son conversiones de imágenes PNG

Sinopsis:

wp webp-express convert [<location>] [--reconvert] [--only-png] [--only-jpeg] [--quality=<number>] [--near-lossless=<number>] [--alpha-quality=<number>] [--encoding=<auto|lossy|lossless>] [--converter=<converter>]
wp webp-express flushwebp [--only-png]

Estoy considerando añadir comandos para ver el estado, ver las estadísticas de conversión, generar los archivos .htaccess y modificar la configuración. Por favor, házmelo saber si necesitas cualquiera de estos o tal vez algo más.

FAQ

How do I verify that the plugin is working?

Verificando que el plugin funcione en el modo de «Respuestas de imagen variadas»
1. Asegúrate de que al menos uno de los métodos de conversión esté funcionando. Debería tener una marca de verificación verde junto a él.
2. Si aún no has guardado, haz clic en «Guardar ajustes». Esto colocará reglas de redirección en archivos .htaccess en los directorios relevantes (generalmente en uploads, themes y wp-content/webp-express/webp-images, dependiendo del ajuste de «Alcance»).
3. Supongo que has marcado al menos una de las casillas de verificación en la sección de reglas .htaccess; de lo contrario, sería mejor cambiar al modo «Amigable con CDN». La primera
4. Haz clic en los botones «Prueba en vivo» para ver si las reglas habilitadas realmente están funcionando. Si no lo están, podría ser que el servidor necesite un poco de tiempo para reconocer las reglas cambiadas.

Las pruebas en vivo son bastante exhaustivas y las recomiendo por encima de una prueba manual. Sin embargo, no está de más hacer también una inspección manual.

Realizar una inspección manual

Ten en cuenta que cuando WebP Express está sirviendo respuestas de imagen variadas, las URL de las imágenes siguen apuntando al jpg/png. Sin embargo, si se visita la URL utilizando un navegador que admite webp, la respuesta será una imagen webp. Por lo tanto, hay una discrepancia entre la extensión del archivo (el nombre de archivo termina en «jpg» o «png») y el tipo de archivo. Pero afortunadamente, el navegador no se basa en la extensión para determinar el tipo de archivo, solo examina la cabecera de respuesta Content-Type.

Para comprobar que el plugin funciona (sin hacer clic en el botón de prueba), haz lo siguiente:

  • Abre la página en un navegador que admita webp, por ejemplo Google Chrome
  • Right-click the page and choose «Inspect»
  • Click the «Network» tab
  • Reload the page
  • Find a jpeg or png image in the list. In the «type» column, it should say «webp»

También puedes revisar las cabeceras. Cuando WebP Express haya redirigido a un archivo webp existente, habrá una cabecera «X-WebP-Express» con el siguiente valor: «Redirigido directamente a webp existente». Si no está presente (y has activado «Habilitar redirección al convertidor»), deberías ver una cabecera «WebP-Convert-Log» (WebP-Express utiliza el convertidor WebP para las conversiones).

No conversions methods are working out of the box

Don’t fret – you have options!

  • If you a controlling another WordPress site (where the local conversion methods DO work), you can set up WebP Express there, and then connect to it by configuring the “Remote WebP Express” conversion method.
  • You can also setup the ewww conversion method. To use it, you need to purchase an api key. They do not charge credits for webp conversions, so all you ever have to pay is the one dollar start-up fee 🙂 (unless they change their pricing – I have no control over that). You can buy an api key here: https://ewww.io/plans/
  • I have written a template letter which you can send to your webhost
  • You can try to get one of the local converters working. Check out this page on the webp-convert wiki. There is also this test/troubleshooting script which is handy when messing around with this.
  • Finally, if you have access to another server and are comfortable with installing projects with composer, you can install webp-convert-cloud-service. It’s open source.

Of course, there is also the option of using another plugin altogether. I can recommend Optimole. If you want to try that out and want to support me in the process, follow this link. It is an affiliate link and will give me a reward in case you decide to sign up.

It doesn’t work – Although test conversions work, it still serves jpeg images

Actually, you might be mistaking, so first, make sure that you didn’t make the very common mistake of thinking that something with the URL example.com/image.jpg must be a jpeg image. The plugin serves webp images on same URL as the original (unconverted) images, so do not let appearances fool you! Confused? See next FAQ item.

Assuming that you have inspected the content type header, and it doesn’t show «image/webp», please make sure that:
1) You tested with a browser that supports webp (such as Chrome)
2) The image URL you are looking at are not pointing to another server (such as gravatar.com)

Assuming that all above is in place, please look at the response headers to see if there is a X-WebP-Convert-Status header. If there isn’t, well, then it seems that the problem is that the image request isn’t handed over to WebP Express. Reasons for that can be:

  • You are on NGINX (or an Apache/Nginx combination). NGINX requires special attention, please look at that FAQ item
  • You are on WAMP. Please look at that FAQ item

I shall write more on this FAQ item… Stay tuned.

How can a webp image be served on an URL ending with «jpg»?

Easy enough. Browsers looks at the content type header rather than the URL to determine what it is that it gets. So, although it can be confusing that the resource at example.com/image.jpg is a webp image, rest assured that the browsers are not confused. To determine if the plugin is working, you must therefore examine the content type response header rather than the URL. See the «How do I verify that the plugin is working?» Faq item.

I am btw considering making an option to have the plugin redirect to the webp instead of serving immediately. That would remove the apparent mismatch between file extension and content type header. However, the cost of doing that will be an extra request for each image, which means extra time and worse performance. I believe you’d be ill advised to use that option, so I guess I will not implement it. But perhaps you have good reasons to use it? If you do, please let me know!

WP CLI, pero ¿cómo lo uso para convertir en lotes?

Bueno, en primer lugar, si no sabes WP CLI, aquí tienes un inicio rápido

WebP Express actualmente soporta comandos para convertir y descargar imágenes webp a través de la CLI. Puede utilizar la opción –help para conocer las opciones:
wp webp-express –help. Muestra los comandos disponibles
wp webp-express convert –help. Muestra las opciones disponibles para el comando «convert».

Algunos ejemplos:
wp webp-express convert: Crea imágenes webp para todas las imágenes no convertidas
wp webp-express convert –reconvert: Convierte también las imágenes ya convertidas
wp webp-express convert themes: Sólo las imágenes de la carpeta themes
wp webp-express convert uploads/2021: Solo las imágenes de la carpeta «2021» dentro de la carpeta uploads
wp webp-express convert –only-png: Solo las imágenes PNG
wp webp-express convert –quality=50: Usar calidad 50 (en lugar de la introducida en la pantalla de configuración)
wp webp-express convert –quality=50 –near-lossless=50 –alpha-quality=50 –encoding=lossy: Más opciones de conversión. La codificación puede ser «lossy», «lossless» o «auto».
wp webp-express convert –converter=cwebp: Utiliza específicamente el convertidor cwebp. Otras opciones: «vips», «imagemagick», «ffmpeg». PD: Para «ewww» y «wpc» (webp express remoto) no funciona aquí.

wp webp-express flushwebp: Eliminar todas las imágenes webp
wp webp-express flushwebp –only-png: Elimina todas las imágenes webp que son conversiones de imágenes PNG

Sinopsis:

wp webp-express convert [<location>] [--reconvert] [--only-png] [--only-jpeg] [--quality=<number>] [--near-lossless=<number>] [--alpha-quality=<number>] [--encoding=<auto|lossy|lossless>] [--converter=<converter>]
wp webp-express flushwebp [--only-png]

Estoy considerando añadir comandos para ver el estado, ver las estadísticas de conversión, generar los archivos .htaccess y modificar la configuración. Por favor, házmelo saber si necesitas cualquiera de estos o tal vez algo más.

Blank images in Safari?

WebP Express has three ways of distributing webp to webp-enabled browsers while still sending the originals to webp-disabled browsers. While method 1 can be combined with any of the other methods, you would usually just pick method 1 or one of the others if method 1 cannot be used for you.

Can some of these go wrong?
Yes. All!

Method 1: Varied image responses
The «Varied image responses» method adds rules to the .htaccess which redirects jpegs and pngs to the corresponding webps (if they exist). The rules have a condition that makes sure they only trigger for browsers supports webp images (this is established by examining the «accept» header).

I the method «varied image responses» because the response on a given image URL varies (the webp is served on the same URL as the jpeg/png).

In the cases where method 1 fails, it is due to systems that cache images by the URL alone. To prevent this from happening, the .htaccess rules adds a Vary:Accept response header. However, most CDNs does not respect that header unless they are configured to do so. Fortunately proxy servers respects it nicely (however often by throwing out the cached image if the accept header doesn’t match)

Method 1 can go wrong if:

  1. You are using a CDN and it hasn’t been set up to handle varied image responses. If this has happened, it is critical that you purge the CDN cache! For information regarding CDN setups, check out the CDN section in this FAQ
  2. Your server doesn’t support adding response headers in .htaccess. On Apache, the «mod_headers» module needs to be enabled. Otherwise the all important Vary:Accept response header will not be set on the response.
  3. Your server doesn’t support SetEnv. However, that module is fortunately very common. I have posted a possible solution to make the rules work without SetEnv here.
  4. You are on Nginx and you haven’t created rules that adds the Vary:Accept header.

I do not believe it can go wrong in other ways. To be certain, please check out this test page. When visiting the test-page with Safari, you should see two images with the “JPG” label over them. When visiting the test-page with a browser that supports webp, you should see two images with the “WEBP” label over them. If you do not see one of these things, please report! (no-one has yet experienced that)

Since WebP Express 0.15.0 you can use the «Live test» button to check that browsers not supporting webp gets the original files and that the Vary:Accept header is returned. Note however that it may not detect CDN caching problems if the CDN doesn’t cache a new image immediately – and across all its nodes.

Method 2: Altering HTML to use picture tags
IMG tags are replaced with PICTURE tags which has two sources. One of them points to the webp and has the «content-type» set to «image/webp». The other points to the original. The browser will select the webp source if it supports webp and the other source if it doesn’t.

Method 2 can go wrong on old browser that doesn’t support the picture tag syntax. However, simply enable the «Dynamically load picturefill.js on older browsers» option, and it will take care of that issue.

Method 3: Altering HTML to point directly to webps in webp enabled browsers
In this solution, the URLs in the HTML are modified for browsers that supports webp. Again, this is determined by examining the «accept» header. So, actually the complete page HTML varies with this method.

Method 3 can go wrong if you are using a page caching plugin if that plugin does not create a separate webp cache for webp-enabled browsers. The Cache Enabler plugin handles this. I don’t believe there are other page caching plugins that does. There is a FAQ section in this FAQ describing how to set Cache Enabler up to work in tandem with WebP Express.

Note that Firefox 66+ unfortunately stopped including «image/webp» in the «accept» header it sends when requesting the page. While Firefox 66+ fortunately still includes «image/webp» in its accept header for images. That will however not get it webp images when using method 3.

I am on NGINX or OpenResty

WebP Express funciona bien en NGINX; sin embargo, la interfaz NGINX de usuario no está optimizada todavía. Y por supuesto, NGINX no procesa los archivos .htaccess que WebP Express genera. WebP Express puede usarse sin redirección, ya que puede alterar el HTML para usar etiquetas de imagen que enlazan con la alternativa webp. Véase «La forma sencilla» más abajo. O, puedes ensuciarte las manos y configurar la redirección en NGINX guiado por la sección «La forma avanzada» a continuación.

The simple way (no redirecting rules)
The easy solution is simply to use the plugin in «CDN friendly» mode, do a bulk conversion (takes care of converting existing images), activate the «Convert on upload» option (takes care of converting new images in the media library) and enable Alter HTML (takes care of delivering webp to webp enabled browsers while still delivering the original jpeg/png to browsers not supporting webp).

PRO: Very easy to set up.
CON: Images in external CSS and images being dynamically added with javascript will not be served as webp.
CON: New new theme images will not be converted until you run a new Bulk conversion

The advanced way (creating NGINX redirecting rules)
Creating NGINX rules requires manually inserting redirection rules in the NGINX configuration file (nginx.conf or the configuration file for the site, found in /etc/nginx/sites-available). If you do not have access to do that, you will have to settle with the «simple way» described above.

There are two different approaches to achieve the redirections. The one that I recommend is based on a try_files directive. If that doesn’t work for you, you can try the alternative rules that are based on the rewrite directive. The rules are described in the next couple of sections.

For multisite on NGINX, read here

Recommended rules (using «try_files»)

Preparational step:
The rules looks for existing webp files by appending «.webp» to the URL. So for this to work, you must configure WebP Express to store the converted files like that by setting General > File extension to Append «.webp»

The rules:
Insert the following in the server context of your configuration file (usually found in /etc/nginx/sites-available). «The server context» refers to the part of the configuration that starts with «server {» and ends with the matching «}».

# WebP Express rules
# --------------------
location ~* ^/?wp-content/.*\.(png|jpe?g)$ {
  add_header Vary Accept;
  expires 365d;
  if ($http_accept !~* "webp"){
    break;
  }
  try_files
    /wp-content/webp-express/webp-images/doc-root/$uri.webp
    $uri.webp
    /wp-content/plugins/webp-express/wod/webp-on-demand.php?xsource=x$request_filename&wp-content=wp-content
    ;
}

# Route requests for non-existing webps to the converter
location ~* ^/?wp-content/.*\.(png|jpe?g)\.webp$ {
    try_files
      $uri
      /wp-content/plugins/webp-express/wod/webp-realizer.php?xdestination=x$request_filename&wp-content=wp-content
      ;
}
# ------------------- (WebP Express rules ends here)

BEWARE:
– Beware that when copy/pasting you might get html-encoded characters. Verify that the ampersand before «wp-content» isn’t encoded (in the last line in the try_files block)

  • Beware that the rules looks for existing webp files by appending «.webp» to the URL. So for this to work, you must configure WebP Express to store the converted files like that.

  • Beware that if you haven’t enabled png conversion, you should replace «(png|jpe?g)» with «jpe?g».

  • Beware that if you have moved wp-content to a non-standard place, you must change accordingly. Note that you must then also change the «wp-content» parameter to the script. It expects a relative path to wp-content (from document root) and is needed so the script can find the configuration file.

  • Beware that there is a hack out there for permalinks which is based on «rewrite» (rather than the usual solution which is based on try_files). If you are using that hack to redirect missing files to index.php, you need to modify it as specified here

  • I have put in an expires statement for caching. You might want to modify or disable that.

  • The rules contains all redirections (as if you enabled all three redirection options in settings). If you do not wish to redirect to converter, remove the last line in the try_files block. If you do not wish to create webp files upon request, remove the last location block.

  • If you have configured WebP Express to store images in separate folder, you do not need the «$uri.webp» line in the first «try_files» block. But it doesn’t hurt to have it. And beware that the reverse is not true. If configured to store images in the same folder («mingled»), you still need the line that looks for a webp in the separate folder. The reason for this is that the «mingled» only applies to the images in the upload folder – other images – such as theme images are always stored in a separate folder.

If you cannot get this to work then perhaps you need to add the following to your mime.types configuration file:
image/webp webp;

If you still cannot get it to work, you can instead try the alternative rules below.

Credits: These rules are builds upon Eugene Lazutkins solution.

Alternative rules (using «rewrite»)

In case the recommended rules does not work for you, you can try these alternative rules.

The reason I recommend the try_files approach above over these alternative rules is that it is a bit simpler and it is supposed to perform marginally better. These alternative rules are in no way inferior to the other. Choose whatever works!

Preparational step:
The rules looks for existing webp files by appending «.webp» to the URL. So for this to work, you must configure WebP Express to store the converted files like that by setting General > File extension to Append «.webp». Also make sure that WebP Express is configured with «Destination» set to «Mingled».

The rules:
Insert the following in the server context of your configuration file (usually found in /etc/nginx/sites-available). «The server context» refers to the part of the configuration that starts with «server {» and ends with the matching «}».

# WebP Express rules
# --------------------
location ~* ^/wp-content/.*\.(png|jpe?g)$ {
    add_header Vary Accept;
    expires 365d;
}
location ~* ^/wp-content/.*\.webp$ {
    expires 365d;
    if ($whattodo = AB) {
        add_header Vary Accept;
    }
}
if ($http_accept ~* "webp"){
    set $whattodo A;
}
if (-f $request_filename.webp) {
    set $whattodo  "${whattodo}B";
}
if ($whattodo = AB) {
    rewrite ^(.*) $1.webp last;
}
if ($whattodo = A) {
    rewrite ^/wp-content/.*\.(jpe?g|png)$ /wp-content/plugins/webp-express/wod/webp-on-demand.php?xsource=x$request_filename&wp-content=wp-content break;
}
# ------------------- (WebP Express rules ends here)

«

BEWARE:

  • Beware that when copy/pasting you might get html-encoded characters. Verify that the ampersand before «wp-content» isn’t encoded (in the last line in the try_files block)

  • Beware that the rules looks for existing webp files by appending «.webp» to the URL. So for this to work, you must configure WebP Express to store the converted files like that.

  • Beware that if you haven’t enabled png conversion, you should replace «(png|jpe?g)» with «jpe?g».

  • Beware that if you have moved wp-content to a non-standard place, you must change accordingly. Note that you must then also change the «wp-content» parameter to the script. It expects a relative path to wp-content (from document root) and is needed so the script can find the configuration file.

  • Beware that there is a hack out there for permalinks which is based on «rewrite» (rather than the usual solution which is based on try_files). If you are using that hack to redirect missing files to index.php, you need to modify it as specified here

  • I have put in an expires statement for caching. You might want to modify or disable that.

  • I have not set any expire on the webp-on-demand.php request. This is not needed, as the script sets this according to what you set up in WebP Express settings. Also, trying to do it would require a new location block matching webp-on-demand.php, but that would override the location block handling php files, and thus break the functionality.

  • There is no longer any reason to add «&$args» to the line begining with «/wp-content». It was there to enable debugging a single image by appending «?debug» to the url. I however removed that functionality from webp-on-demand.php.

It is possible to put this stuff inside a location directive. However, having if directives inside location directives is considered evil. But it seems that in our case, it works. If you wish to do that, use the following rules instead:

# WebP Express rules
# --------------------
location ~* ^/wp-content/.*\.(png|jpe?g)$ {
    add_header Vary Accept;
    expires 365d;

    if ($http_accept ~* "webp"){
        set $whattodo A;
    }
    if (-f $request_filename.webp) {
        set $whattodo  "${whattodo}B";
    }
    if ($whattodo = AB) {
        rewrite ^(.*) $1.webp last;
    }
    if ($whattodo = A) {
        rewrite ^/wp-content/.*\.(jpe?g|png)$ /wp-content/plugins/webp-express/wod/webp-on-demand.php?xsource=x$request_filename&wp-content=wp-content last;
    }
}

location ~* ^/wp-content/.*\.webp$ {
    expires 365d;
    if ($whattodo = AB) {
        add_header Vary Accept;
    }
}
# ------------------- (WebP Express rules ends here)

PS: In case you only want to redirect images to the script (and not to existing), the rules becomes much simpler:

# WebP Express rules
# --------------------
if ($http_accept ~* "webp"){
  rewrite ^/(.*).(jpe?g|png)$ /wp-content/plugins/webp-express/wod/webp-on-demand.php?xsource=x$request_filename&wp-content=wp-content break;
}
# ------------------- (WebP Express rules ends here)

Discussion on this topic here
And here: https://github.com/rosell-dk/webp-express/issues/166

Here are rules if you need to replace the file extension with «.webp» rather than appending «.webp» to it: https://www.keycdn.com/support/optimus/configuration-to-deliver-webp

I am on a Windows server

Good news! It should work now, thanks to a guy that calls himself lwxbr. At least on XAMPP 7.3.1, Windows 10. https://github.com/rosell-dk/webp-express/pull/213.

I am on a Litespeed server

You do not have to do anything special for it to work on a Litespeed server. You should be able to use WebP Express in any operation mode. For best performance, I however recommend that use the LiteSpeed Cache plugin for page caching.

LiteSpeed Cache can be set up to maintain separate page caches for browsers that supports webp and browsers that don’t. Through this functionality it is possible to use «Alter HTML» with the option «Replace image URLs» and «Only do the replacements in webp enabled browsers» mode.

The setup was kindly shared and explained in detail by @ribeiroeder here

I am using Jetpack

If you install Jetpack and enable the «Speed up image load times» then Jetpack will alter the HTML such that images are pointed to their CDN.

Ie:

becomes:

Jetpack automatically serves webp files to browsers that supports it using same mechanism as the standard WebP Express configuration: If the «Accept» header contains «image/webp», a webp is served (keeping original file extension, but setting the «content-type» header to «image/webp»), otherwise a jpg is served.

As images are no longer pointed to your original server, the .htaccess rules created by WebP Express will not have any effect.

So if you are using Jetpack you don’t really need WebP Express?
Well, there is no point in having the «Speed up image load times» enabled together with WebP Express.

But there is a case for using WebP Express rather than Jetpacks «Speed up image load times» feature:

Jetpack has the same drawback as the standard WebP Express configuration: If a user downloads the file, there will be a mismatch between the file extension and the image type (the file is ie called «logo.jpg», but it is really a webp image). I don’t think that is a big issue, but for those who do, WebP Express might still be for you, even though you have Jetpack. And that is because WebP Express can be set up just to generate webp’s, without doing the internal redirection to webp (will be possible from version 0.10.0). You can then for example use the Cache Enabler plugin, which is able to generate and cache two versions of each page. One for browsers that accepts webp and one for those that don’t. In the HTML for webp-enabled browsers, the images points directly to the webp files.

Pro Jetpack:
– It is a free CDN which serves webp out of the box.
– It optimizes jpegs and pngs as well (but note that only about 1 out of 5 users gets these, as webp is widely supported now)

Con Jetpack:
– It is a big plugin to install if you are only after the CDN
– It requires that you create an account on WordPress.com

Pro WebP Express:
– You have control over quality and metadata
– It is a small plugin and care has been taken to add only very little overhead
– Plays well together with Cache Enabler. By not redirecting jpg to webp, there is no need to do any special configuration on the CDN and no issue with misleading file extension, if user downloads a file.

Con WebP Express:
– If you are using a CDN and you are redirecting jpg to webp, you must configure the CDN to forward the Accept header. It is not possible on all CDNs.

Why do I not see the option to set WebP quality to auto?

The option will only display, if your system is able to detect jpeg qualities. To make your server capable to do that, install Imagick extension (PECL >= 2.2.2) or enable exec() calls and install either Imagick or Gmagick.

If you have the Imagick, the Imagick binary or the Remote WebP Express conversion method working, but don’t have the global «auto» option, you will have the auto option available in options of the individual converter.

Note: If you experience that the general auto option doesn’t show, even though the above-mentioned requirements should be in order, check out this support-thread.

How do I configure my CDN in «Varied image responses» operation mode?

In Varied image responses operation mode, the image responses varies depending on whether the browser supports webp or not (which browsers signals in the Accept header). Some CDN’s support this out of the box, others requires some configuration and others doesn’t support it at all.

For a CDN to cooperate, it needs to
1) forward the Accept header and
2) Honour the Vary:Accept response header.

You can also make it «work» on some CDN’s by bypassing cache for images. But I rather suggest that you try out the CDN friendly mode (see next FAQ item)

Status of some CDN’s:

  • KeyCDN: Does not support varied image responses. I have added a feature request here. You can give it a +1 if you like!
  • Cloudflare: See the «I am on Cloudflare» section
  • Cloudfront: Works, but needs to be configured to forward the accept header. Go to Distribution settings, find the Behavior tab, select the Behavior and click the Edit button. Choose Whitelist from Forward Headers and then add the «Accept» header to the whitelist.

I shall add more to the list. You are welcome to help out here.

How do I make it work with CDN? («CDN friendly» mode)

In CDN friendly mode, there is no trickery with varied image responses, so no special attention is required on the CDN.

However, there are other pitfalls.

The thing is that, unless you have the whole site on a CDN, you are probably using a plugin that alters the HTML in order to point your static assets to the CDN. If you have enabled the «Alter HTML» in WebP Express, it means that you now have two alterations on the image URLs!

How will that play out?

Well, if WebP Express gets to alter the HTML after the image URLs have been altered to point to a CDN, we have trouble. WebP Express does not alter external images but the URLs are now external.

However, if WebP Express gets to alter the HTML before the other plugin, things will work fine.

So it is important that WebP Express gets there first.

The good news is that WebP Express does get there first on all the plugins I have tested.

But what can you do if it doesn’t?

Firstly, you have an option in WebP Express to select between:
1. Use content filtering hooks (the_content, the_excerpt, etc)
2. The complete page (using output buffering)

The content filtering hooks gets to process the content before output buffering does. So in case output buffering isn’t early enough for you, choose the content filtering hooks.

There is a risk that you CDN plugin also uses content filtering hooks. I haven’t encountered any though. But if there is any out there that does, chances are that they get to process the content before WebP Express, because I have set the priority of these hooks quite high (10000). The reasoning behind this is to that we want to replace images that might be inserted using the same hook (for example, a theme might use the_content filter to insert the featured image). If you do encounter a plugin for changing URLs for CDN which uses the content filtering hooks, you are currently out of luck. Let me know, so I can fix that (ie. by making the priority configurable)

Here are a list of some plugins for CDN and when they process the HTML:

Plugin
Method
Hook(s)
Priority

BunnyCDN
Output buffering
template_redirect
default (10)

CDN enabler
Output buffering
template_redirect
default (10)

Jetpack
content filtering
the_content, etc
the_content: 10

W3 Total Cache
Output buffering
no hooks. Buffering is started before hooks

WP Fastest Cache
Output buffering
no hooks. Buffering is started before hooks

WP Super Cache
Output buffering
init
default (10)

With output buffering the plugin that starts the output buffering first gets to process the output last. So WebP Express starts as late as possible, which is on the template_redirect hook, with priority 10000 (higher means later). This is later than the init hook, which is again later than the no hooks.

I am on Cloudflare

Without configuration, Cloudflare will not maintain separate caches for jpegs and webp; all browsers will get jpeg. To make Cloudflare cache not only by URL, but also by header, you need to use the Custom Cache Key page rule, and add Header content to make separate caches depending on the Accept request header.

However, the Custom Cache Key rule currently requires an Enterprise account. And if you already have that, you may as well go with the Polish feature, which starts at the “Pro” level plan. …

Reseñas

3 de abril de 2024
This WordPress plugin is working really well for me on a Multisite setup with Subdirectories. Additionally, I’ve configured a custom folder for image uploads in the root directory, outside of the wp-content folder. All of this is installed on a server running Debian OS, Plesk Panel, and Nginx. To achieve this, I had to tweak the Nginx configuration in Plesk, specifically in the «Web and Domains» section and then in «Apache and Nginx Settings» within the Plesk control panel. Here, I was able to input the Nginx configuration code as per the instructions provided by the plugin developer. While the first configuration option for Nginx didn’t work for me, the second option of «Alternative rules (using ‘rewrite’)» did. Now, with WordPress Multisite set up with subdirectories and a custom uploads folder, the webp images are served seamlessly, redirecting to JPG in older browsers. I really appreciate the effort put in by the plugin developer to provide these configuration options and make everything work smoothly. Thank you very much.
3 de abril de 2024
This plugin has an impressive amount of features and configuration options when it comes to converting and delivering WebP images. However, this can also be intimidating, and the UI is quite dry and technical. Highly recommended for advanced users, but maybe not the right choice for the avarage WordPress user.
31 de octubre de 2023
Converted only few files. Thanks God did not brake anything for a while. The only question: WHY this is here?!
31 de octubre de 2023
Está falhando na instalação, tanto via painel do admin quanto enviando o plugin diretamente via FTP. Uma pena, pois etilizei em diversos projetos.
Leer todas las 155 reseñas

Colaboradores y desarrolladores

«WebP Express» es un software de código abierto. Las siguientes personas han colaborado con este plugin.

Colaboradores

«WebP Express» está traducido en 23 idiomas. Gracias a los traductores por sus contribuciones.

Traduce «WebP Express» a tu idioma.

¿Interesado en el desarrollo?

Revisa el código , echa un vistazo al repositorio SVN o suscríbete al registro de desarrollo por RSS.

Registro de cambios

0.25.9

(released 7 April 2024)
* Bugfix: Fixed ewww conversion method after ewww API change

0.25.8

(released 20 October 2023)
* Bugfix: Depreciation warning on PHP 8.2 with Alter HTML. Thanks to @igamingsolustions for reporting the bug

0.25.7

(released 19 October 2023)
* Bugfix: Removed depreciation warning on settings screen, which was showing in PHP 8.2. Thanks to Rob Meijerink from the Netherlands for providing the fix in a pull request
* Bugfix: Removed depreciation warning when converting, happening in PHP 8.2. Thanks to Sophie B for reporting and Rob Meijerink from the Netherlands for providing the fix in a pull request
* Bugfix: One of the Mime fallback methods did not work. Thanks to gerasart from Ukraine for providing the fix in a pull request

0.25.6

(released 15 April 2023)
* Bugfix: A bug in another plugin can cause delete file hook to be called with an empty string, which WebP Express was not prepared for (fatal exception). Thanks to Colin Frick from Liechtenstein for providing the fix in a pull request on github
* Bugfix: Bug when testing imagick converter from settings page (only PHP 8). Thanks to Sisir from Bangladesh for reporting and providing the fix in a pull request

0.25.5

(released 23 May 2022)
* When using the «Prevent using webps larger than original» with Alter HTML (picture tags) on images with srcset, those webps that where larger than the originals was picked out from the srcset for the webp. This could lead to bad quality images. In the fix, the image will only have a webp source alternative when ALL the webps are smaller than their originals (when the «prevent…» option is set).
* Bugfix: In rare cases, WebP Express could fail detecting mime type

0.25.4

(released 6 May 2022)
* AlterHTML (when using picture tags): Fixed charset problems for special characters in alt and title attributes. The bug was introduced in 0.25.2. Thanks to Cruglk for first pointing this out.

0.25.3

(released 4 May 2022)
* AlterHTML: Fixed BIG BUG introduced in 0.25.2 (the webp urls was wrong when using picture tags). So sorry! Thankfully, I was quickly made aware of this and quickly patched it.

0.25.2

(released 4 May 2022)
* AlterHTML did not skip existing picture tags when they contained newlines, resulting in picture tags inside picture tags, which is invalid markup. Thanks to Jonas for being very helpful in solving this.

0.25.1

(released 7 dec 2021)
* An innocent text file triggered Windows Defender. It has been removed. Thanks to Javad Naroogheh from Iran for notifying

0.25.0

(released 7 dec 2021, on my daughters 10 year birthday!)
* No exec()? – We don’t give up easily, but now emulates it if possible, using proc_open(), passthru() or other alternatives. The result is that the cwebp converter now is available on more systems. Quality detection of jpegs also works on more systems now. The fallback feature with the emulations is btw implemented in a new library, exec-with-fallback
* Bugfix: Our WP CLI command «webp-express» has a quality option, but it was not working

For older releases, check out changelog.txt