Plesk

How to configure nginx to serve .webp images instead of .jpg/.png for a domain on nginx only in Plesk

Question

How to configure nginx to serve .webp images instead of jpg/png images when the website is running on nginx only?

Answer

In this example, we have a WebP copy of a jpg/png image with .webp extension next to the original file, for example:

 

  1. Connect to the Plesk server via SSH.

  2. Create the file /etc/nginx/conf.d/webp.conf :

    # touch /etc/nginx/conf.d/webp.conf

  3. Open the webp.conf file in a text editor (for example, vi editor) and paste the following content in it:

    map $http_accept $webp_extension { default ""; "~*webp" ".webp"; }

  4. Save the changes and close the file.

  5. Restart the nginx service to apply the changes:

    # service nginx restart

  6. Log in to Plesk and go to Domains > example.com > Apache & nginx settings.

  7. Add the following to the additional nginx directives field:

    location ~* ^.+.(jpe?g|png) {
        add_header Cache-Control "public, no-transform";
        add_header Vary "Accept-Encoding";
        if ( !-f $document_root$uri$webp_extension ) {
                add_header X_WebP_SP_Miss $document_root$uri$webp_extension;
            }
        try_files $uri$webp_extension $uri =404;
    }

  8. Make sure Serve static files directly by nginx checkbox is disabled.
  9. Apply the changes.