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

  1. Open your site's server block (the server { ... } section of your NGINX config).

  2. Paste the following inside it. It checks the browser's Accept header (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;
    }
  3. Test the config and reload NGINX so the change takes effect.

    bash
    sudo nginx -t && sudo systemctl reload nginx
  4. Verify in your browser. Open the network panel, reload an image-heavy page, and check the Content-Type of an image request. A current Chrome or Firefox should report image/avif or image/webp.

What can go wrong

  • The browser still receives the JPEG or PNG. The location regex only matches .png, .jpg, and .jpeg paths 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?.

See also

Was this helpful?