0
0
Nginxdevops~15 mins

Wildcard and regex server names in Nginx - Deep Dive

Choose your learning style9 modes available
Overview - Wildcard and regex server names
What is it?
Wildcard and regex server names in nginx let you match multiple domain names with a single rule. Wildcards use simple patterns like *.example.com to catch all subdomains. Regex server names use regular expressions for more flexible and complex matching. This helps nginx decide which website configuration to use based on the requested domain.
Why it matters
Without wildcard or regex server names, you would need a separate configuration for every domain or subdomain. This would be hard to manage and error-prone, especially for sites with many subdomains or dynamic names. Using these patterns saves time, reduces mistakes, and makes your server setup scalable and easier to maintain.
Where it fits
Before learning this, you should understand basic nginx server blocks and how server_name works with exact domain names. After mastering wildcards and regex, you can explore advanced nginx features like load balancing, SSL configuration per domain, and dynamic routing.
Mental Model
Core Idea
Wildcard and regex server names let nginx match many domain names with one pattern to choose the right website configuration.
Think of it like...
It's like having a mailbox labeled 'All Apartments' instead of one for each apartment number, so mail for any apartment in the building goes to the same place.
┌───────────────────────────────┐
│ nginx Server Block Selection   │
├───────────────┬───────────────┤
│ Exact Name    │ example.com   │
│ Wildcard      │ *.example.com│
│ Regex         │ ~^www\d+\.example\.com$ │
└───────────────┴───────────────┘

Request domain → Matches one of above → Uses matching server block
Build-Up - 7 Steps
1
FoundationBasic server_name usage
🤔
Concept: Learn how nginx matches exact domain names using server_name.
In nginx, the server_name directive tells which domain names a server block responds to. For example: server { listen 80; server_name example.com www.example.com; root /var/www/example; } This block handles requests for example.com and www.example.com exactly.
Result
nginx serves the website only when the request matches example.com or www.example.com exactly.
Understanding exact matching is the base for grasping how wildcards and regex extend this matching.
2
FoundationIntroduction to wildcard server names
🤔
Concept: Learn how to use simple wildcard patterns to match multiple subdomains.
Wildcards use * to match any part of a domain. For example: server { listen 80; server_name *.example.com; root /var/www/subdomains; } This matches any subdomain like blog.example.com or shop.example.com but not example.com itself.
Result
nginx serves the same content for all subdomains of example.com matched by the wildcard.
Wildcards simplify configuration by grouping many subdomains under one rule.
3
IntermediateWildcard position rules and limitations
🤔Before reading on: Do you think you can put a wildcard anywhere in the domain name, like example.*.com? Commit to your answer.
Concept: Understand where wildcards can be placed and what is allowed in nginx server names.
In nginx, wildcards can only be at the start or end of a domain part: - *.example.com matches subdomains - example.* is invalid - *example.com is invalid Also, only one wildcard per server_name is allowed. Wildcards match exactly one domain part, not multiple parts.
Result
You learn the correct syntax and avoid invalid wildcard patterns that cause nginx errors.
Knowing wildcard placement rules prevents configuration errors and unexpected matching behavior.
4
IntermediateRegex server names basics
🤔Before reading on: Do you think regex server names are checked before or after exact and wildcard names? Commit to your answer.
Concept: Learn how to use regular expressions to match complex domain patterns in nginx.
Regex server names start with ~ and use standard regular expressions. For example: server { listen 80; server_name ~^www\d+\.example\.com$; root /var/www/numbered; } This matches www1.example.com, www23.example.com, etc. Regex allows very flexible matching beyond wildcards.
Result
nginx can route requests to server blocks based on complex domain patterns using regex.
Regex server names unlock powerful matching but require careful pattern design.
5
IntermediateMatching order and priority
🤔Before reading on: Does nginx check regex server names before exact or wildcard names? Commit to your answer.
Concept: Understand the order nginx uses to match server names: exact, wildcard, then regex.
nginx matches server names in this order: 1. Exact names 2. Longest wildcard starting with * 3. Longest wildcard ending with * 4. Regex names This means exact matches have highest priority, regex last. If multiple regex match, the first defined wins.
Result
You can predict which server block will handle a request when multiple patterns match.
Knowing matching order helps avoid surprises and conflicts in server configuration.
6
AdvancedCombining wildcards and regex in configs
🤔Before reading on: Can you use multiple regex server_name directives in one nginx config? Commit to your answer.
Concept: Learn how to mix exact, wildcard, and regex server names in one nginx setup safely.
You can define multiple server blocks with different server_name types: server { server_name example.com; } server { server_name *.example.com; } server { server_name ~^www\d+\.example\.com$; } nginx picks the best match based on order. Avoid overlapping regex patterns to prevent confusion.
Result
Your nginx config can handle many domain patterns cleanly and efficiently.
Combining patterns lets you cover all domain cases without duplication or errors.
7
ExpertPerformance and security considerations
🤔Before reading on: Do regex server names impact nginx performance significantly? Commit to your answer.
Concept: Understand how regex matching affects nginx speed and security risks of careless patterns.
Regex matching is slower than exact or wildcard because it runs a pattern engine on each request. Complex or poorly written regex can cause delays or even denial of service if exploited. Use regex only when necessary and keep patterns simple. Also, avoid overlapping regex that can cause unpredictable routing.
Result
You write efficient and safe nginx configs that scale well under load.
Knowing regex costs and risks helps you balance flexibility with performance and security.
Under the Hood
nginx stores server_name directives in a special data structure optimized for fast lookup. Exact names use hash tables for O(1) matching. Wildcards are stored in tries (prefix or suffix trees) to quickly match patterns like *.example.com. Regex names are compiled into finite automata and tested sequentially after exact and wildcard checks. This layered approach balances speed and flexibility.
Why designed this way?
nginx was designed for high performance and low latency. Exact and wildcard matches are fast because they cover most use cases. Regex support was added later for advanced needs but kept last in order to avoid slowing down common requests. This design avoids expensive regex checks unless necessary, preserving nginx's speed advantage.
┌───────────────┐
│ Incoming HTTP │
│ Request Host  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Exact Match   │───Yes──▶ Use matched server block
└──────┬────────┘
       │No
       ▼
┌───────────────┐
│ Wildcard Match│───Yes──▶ Use matched server block
└──────┬────────┘
       │No
       ▼
┌───────────────┐
│ Regex Match   │───Yes──▶ Use matched server block
└──────┬────────┘
       │No
       ▼
┌───────────────┐
│ Default Server│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does *.example.com match example.com itself? Commit to yes or no.
Common Belief:Many think that *.example.com matches example.com and all its subdomains.
Tap to reveal reality
Reality:*.example.com matches only subdomains like blog.example.com, not example.com itself.
Why it matters:Misunderstanding this causes nginx to serve the wrong site or fallback to the default server unexpectedly.
Quick: Are regex server names checked before exact names? Commit to yes or no.
Common Belief:Some believe regex server names have the highest priority and override exact matches.
Tap to reveal reality
Reality:nginx always checks exact names first, then wildcards, and regex last.
Why it matters:Incorrect assumptions lead to confusing routing and debugging headaches.
Quick: Can you put a wildcard anywhere in the domain name? Commit to yes or no.
Common Belief:People often think wildcards can be placed anywhere, like example.*.com or *example.com.
Tap to reveal reality
Reality:nginx only allows wildcards at the start or end of a domain part, like *.example.com. Patterns like example.* or *example.com are invalid.
Why it matters:Invalid wildcard placement causes nginx to fail to start or ignore the server block.
Quick: Does using many regex server names always slow down nginx significantly? Commit to yes or no.
Common Belief:Some assume any regex use drastically reduces nginx performance.
Tap to reveal reality
Reality:Regex matching is slower than exact or wildcard but usually negligible if used sparingly and patterns are simple.
Why it matters:Overestimating regex cost may prevent using powerful matching when appropriate.
Expert Zone
1
nginx caches the results of server_name matching per connection, so repeated requests to the same domain are faster after the first match.
2
Regex server names can use capture groups to extract parts of the domain for use in other directives like proxy_pass or rewrite.
3
Wildcard server names only match one domain part; they do not match multiple levels like *.sub.example.com does not match a.b.sub.example.com.
When NOT to use
Avoid regex server names when simple wildcards or exact names suffice, as regex adds complexity and slight performance cost. For very dynamic domain matching, consider using a map directive or external DNS-based routing instead.
Production Patterns
In production, use exact names for main domains, wildcards for broad subdomain coverage, and regex only for special cases like numbered hosts. Combine with SSL certificates using Subject Alternative Names or wildcard certs. Monitor logs to ensure expected matching and avoid overlapping regex patterns.
Connections
DNS Wildcard Records
Similar pattern matching concept
Understanding DNS wildcards helps grasp how nginx wildcards match domain names at the server level.
Regular Expressions in Programming
Regex server names use the same regex syntax and principles
Knowing regex basics from programming makes writing nginx regex server names easier and less error-prone.
Firewall Rules Matching
Both use pattern matching to filter or route traffic
Recognizing that nginx server_name matching and firewall rules share pattern matching logic helps understand network traffic control.
Common Pitfalls
#1Using *.example.com to match example.com itself
Wrong approach:server_name *.example.com;
Correct approach:server_name example.com *.example.com;
Root cause:Misunderstanding that wildcard only matches subdomains, not the root domain.
#2Placing wildcard in the middle of domain name
Wrong approach:server_name example.*.com;
Correct approach:server_name *.example.com;
Root cause:Not knowing nginx only allows wildcards at start or end of domain parts.
#3Overlapping regex patterns causing unpredictable routing
Wrong approach:server_name ~^www\d+\.example\.com$; server_name ~^www[abc]\.example\.com$;
Correct approach:Use distinct regex patterns or combine into one carefully: server_name ~^(www\d+|www[abc])\.example\.com$;
Root cause:Lack of regex pattern planning leads to conflicts and hard-to-debug behavior.
Key Takeaways
nginx server_name supports exact, wildcard, and regex patterns to match domain names flexibly.
Wildcards only match one domain part and cannot replace the root domain itself.
nginx matches server names in order: exact first, then wildcards, then regex last.
Regex server names offer powerful matching but should be used carefully to avoid performance and security issues.
Combining these patterns properly makes nginx configurations scalable, maintainable, and efficient.