How do I configure NGINX to serve WebP and AVIF?
2 min read · Last updated June 2026
On NGINX the plugin can't write delivery rules for you the way it does with Apache's .htaccess. Instead, add a small location block to your server config that serves the AVIF or WebP version of an image when the visitor's browser supports it, and falls back to the JPEG or PNG otherwise.
Prerequisites
- Shell access to edit your NGINX config, and permission to reload the server.
- The plugin has already generated WebP and AVIF files. Confirm in the Media Library that images show a WebP or AVIF variant.
Add the rewrite block
-
Open your site's server block (the
server { ... }section of your NGINX config). -
Paste the following inside it. It checks the browser's
Acceptheader (the list of formats the browser says it supports) and serves the best available format.nginx # Serve AVIF, then WebP, then the original location ~* ^/wp-content/.+\.(png|jpe?g)$ { set $ext ""; if ($http_accept ~* "image/webp") { set $ext .webp; } if ($http_accept ~* "image/avif") { set $ext .avif; } add_header Vary Accept; try_files $uri$ext $uri =404; } -
Test the config and reload NGINX so the change takes effect.
bash sudo nginx -t && sudo systemctl reload nginx -
Verify in your browser. Open the network panel, reload an image-heavy page, and check the
Content-Typeof an image request. A current Chrome or Firefox should reportimage/aviforimage/webp.
What can go wrong
- The browser still receives the JPEG or PNG. The
locationregex only matches.png,.jpg, and.jpegpaths under/wp-content/. If your media lives elsewhere, adjust the path so it matches your files. - The same format reaches every visitor. That's the Cloudflare caching problem above - see the warning, and Why doesn't server rewrite work behind Cloudflare?.