Nginx Wildcard SSL with WordPress Multisite Subdomains

You can use regular expressions in the server_name directive, but wildcard names (e.g. *.example.com) take precedence. See this document for details.

For example:

server {
    listen [::]:80 ipv6only=off;
    server_name ~^(www\.)?(?<name>(.+\.)?example\.com)$;
    return 301 https://$name$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;

    server_name ~^www\.(?<name>(.+\.)?example\.com)$;
    return 301 https://$name$request_uri;
}

server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;

    ...
}

The first server block matches http requests to any subdomain, and redirects to the non-www variant using https.

The second server block matches https requests to subdomains which begin with www. and redirects to the non-www variant.

The third server block does not need a server_name directive (as it is the default server) and handles all https requests to the main domain and non-www subdomains.