0

I am using WordOps script to setup my LEMP server. It already has the rules to serve .webp and .avif images and I’ve generated the .webp and .avif images on my website.

The problem is Edge browser does not support .avif image and it will display blank instead of load .webp or jpg image.

Other browsers such as Chome and Firefox loaded .avif very well and the site runs fast.

I need to rewrite the Nginx rules so when people open my website using Edge or Safari it will load the supported image files as .webp or .jpg instead of .avif.

Below are the current rules:

# webp rewrite rules for jpg and png images
# try to load alternative image.png.webp before image.png
location /wp-content/uploads {
   location ~ \.(png|jpe?g)$ {
       add_header Vary "Accept-Encoding";
       more_set_headers 'Access-Control-Allow-Origin : *';
       more_set_headers  "Cache-Control : public, no-transform";
       access_log off;
       log_not_found off;
       expires max;
       try_files $uri$webp_suffix $uri$avif_suffix $uri =404;
   }

I found a good condition rules here https://vincent.bernat.ch/en/blog/2021-webp-avif-nginx

http {
  map $http_accept $webp_suffix {
    default        "";
    "~image/webp"  ".webp";
  }
  map $http_accept $avif_suffix {
    default        "";
    "~image/avif"  ".avif";
  }
}
server {
  # […]
  location ~ ^/images/.*\.(png|jpe?g)$ {
    add_header Vary Accept;
    try_files $uri$avif_suffix$webp_suffix $uri$avif_suffix $uri$webp_suffix $uri =404;
  }
}

However, I can’t merge the rules to make it work on my site. I always get Nginx errors.

The rules are in the file wpcommon-php74.conf.

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

1

Here are the rules I finished with after several unsuccessful attempts for one of my sites just a few days ago:

map $http_accept $check_avif {
    ~image/avif  "$uri.avif";
}

map $http_accept $check_webp {
    ~image/webp  "$uri.webp";
}

server {
    ...
    location ~ \.(png|jpe?g)$ {
        add_header Vary Accept;
        try_files $check_avif $check_webp $uri =404;
    }
}

For a single image I have the following set of files:

image.jpg
image.jpg.avif
image.jpg.webp
Ivan Shatsky
  • 13,267
  • 2
  • 21
  • 37
  • Two things to improve upon this a bit: 1. The ```map``` directives need to go under the ```http``` directive in your ```nginx.conf``` file. 2. The ```~image/avif``` part in the ```map``` directives needs to be wrapped in quotes, like so: ```"~image/avif"``` – nchopra Sep 14 '22 at 11:50