server {
server_name *.example.com;
listen 80;
}Remember that *.example.com matches one subdomain level only.
The wildcard *.example.com matches any single subdomain like api.example.com, but not the root domain example.com or multiple subdomain levels like sub.api.example.com.
server {
server_name ~^www\.(.+)\.example\.com$;
listen 80;
}The regex matches hostnames starting with www. and ending with .example.com.
The regex ^www\.(.+)\.example\.com$ matches hostnames like www.api.example.com but not api.example.com (missing www), www.example.com (missing subdomain between www and example), or www.api.example.net (wrong domain).
sub.api.example.com?Think about how to match zero or more subdomain levels with regex.
The regex ~^(.+\.)?example\.com$ matches example.com and any subdomain including multiple levels like sub.api.example.com. The wildcard *.example.com only matches one subdomain level.
example.com are not handled by this block. Why?Think about what *.example.com matches.
The wildcard *.example.com matches only subdomains like api.example.com. It does not match the root domain example.com itself, so requests to example.com are not handled by this block.
Exact matches have highest priority, regex lowest.
Nginx prioritizes server_name matches in this order: exact names first, then longest wildcard starting with an asterisk, then longest wildcard ending with an asterisk, and finally regex matches. So exact match example.com should be first, then wildcard, then regex.