cancel
Showing results for 
Search instead for 
Did you mean: 

Conditionally serve webp images with NGINX and Magento 2

Highlighted

Conditionally serve webp images with NGINX and Magento 2

Hello,

Im in trouble understanding how to serve images on Magento 2 with NGINX. Everything works correctly until there is no JPG file on Magento media cache and its needed to generate with

location @media { try_files $uri $uri/ /get.php$is_args$args; }

When i added this #webp block to nginx config then it no longer process below that #images block and if i remove #webp block again media cache will be generated with @Media like it should by default.

My goal is serve webp images ( generated with separate script to original jpg/png location, only difference file extension) and when there is no picture on media cache folder then it will be generated like Magento does by default

Question is how to combine these two #webp and #images...

location /media/ { 

     #webp
        location ~* ^(/media/.+)\.(png|jpe?g)$ {
               set $base $1;
               set $webp_uri $base$webp_suffix;
               set $webp_old_uri $base.$2$webp_suffix;
               set $root "/var/www/magento/htdocs/pub/";
               root $root;
               expires 60s;
               add_header Cache-Control "public";
               add_header Vary Accept;
                if ( !-f $root$webp_uri ) {
                       add_header X_WebP_SP_Miss $root$webp_uri;
                 }
               try_files $webp_uri $webp_old_uri $uri $uri/ @media ;
       }       


     # images css js (default magento block)
        location ~* \.(jpg|jpeg|png|webp|gif|svg|js|css|ico|txt)$ {
              expires max;
              add_header Cache-Control "public";
              try_files $uri $uri/ @media;
        }


     ## fonts
    
        location ~* \.(swf|eot|ttf|otf|woff|woff2)$ {
             expires max;
             add_header Cache-Control "public";
             try_files $uri $uri/ @media;
       }

       try_files $uri $uri/ @media;


  }

      location @static { rewrite /static/(version\d*/)?(.*)$ /static.php?resource=$2 last; }
      location @media { try_files $uri $uri/ /get.php$is_args$args; }