Bird
Raised Fist0
Nginxdevops~15 mins

Wildcard and regex server names in Nginx - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What does a wildcard server name like *.example.com match in nginx?
easy
A. Any domain ending with example.com, including example.com itself
B. Only the exact domain example.com
C. Any subdomain of example.com, like blog.example.com or shop.example.com
D. Only domains starting with a star character

Solution

  1. Step 1: Understand wildcard usage in server names

    A wildcard * before a domain matches any subdomain part, but not the root domain itself.
  2. Step 2: Apply to *.example.com

    This matches domains like blog.example.com or shop.example.com, but not example.com alone.
  3. Final Answer:

    Any subdomain of example.com, like blog.example.com or shop.example.com -> Option C
  4. Quick Check:

    Wildcard * matches subdomains only [OK]
Hint: Wildcard * matches subdomains, not the root domain [OK]
Common Mistakes:
  • Thinking wildcard matches the root domain
  • Confusing wildcard with regex syntax
  • Assuming wildcard matches any domain ending
2. Which of the following is the correct syntax to define a regex server name in nginx?
easy
A. server_name /www\d+\.example\.com/;
B. server_name *example.com;
C. server_name ^www\d+\.example\.com$;
D. server_name ~^www\d+\.example\.com$;

Solution

  1. Step 1: Recall regex server name syntax in nginx

    Regex server names start with a tilde ~ followed by the regex pattern.
  2. Step 2: Check each option

    server_name ~^www\d+\.example\.com$; uses ~^www\d+\.example\.com$ which is correct regex syntax. Others either miss the tilde or use invalid delimiters.
  3. Final Answer:

    server_name ~^www\d+\.example\.com$; -> Option D
  4. Quick Check:

    Regex server names start with ~ [OK]
Hint: Regex server names always start with ~ in nginx [OK]
Common Mistakes:
  • Omitting the ~ before regex pattern
  • Using * instead of ~ for regex
  • Using slashes / / as regex delimiters
3. Given this nginx config snippet:
server {
  server_name ~^www\d+\.example\.com$;
  return 200 'Matched regex server name';
}

What will be the response for a request to www12.example.com?
medium
A. Matched regex server name
B. 500 Internal Server Error
C. 404 Not Found
D. Default nginx welcome page

Solution

  1. Step 1: Understand the regex pattern

    The regex ^www\d+\.example\.com$ matches domains starting with 'www' followed by one or more digits, then '.example.com'.
  2. Step 2: Check if 'www12.example.com' matches

    'www12.example.com' matches the pattern because '12' are digits after 'www'.
  3. Final Answer:

    Matched regex server name -> Option A
  4. Quick Check:

    Regex matches www12.example.com [OK]
Hint: Check if domain fits regex pattern exactly [OK]
Common Mistakes:
  • Assuming regex matches partial strings
  • Ignoring start ^ and end $ anchors
  • Confusing regex with wildcard matching
4. You wrote this nginx config:
server {
  server_name ~www\d+\.example\.com$;
  return 200 'Hello';
}

Why is this regex server_name directive incorrect?
medium
A. Missing ^ anchor at start of regex
B. Regex server name must start with ~ and pattern must start with ^
C. Regex pattern missing delimiters like / /
D. Regex server name must start with ~ and pattern must be valid

Solution

  1. Step 1: Check regex server_name syntax

    Regex server names must start with ~ and the pattern should start with ^ to match from the beginning.
  2. Step 2: Identify missing ^ anchor

    The pattern www\d+\.example\.com$ lacks the ^ anchor, causing partial matches rather than full hostname matches.
  3. Final Answer:

    Regex server name must start with ~ and pattern must start with ^ -> Option B
  4. Quick Check:

    Regex patterns need ^ anchor at start [OK]
Hint: Regex patterns should start with ^ for nginx server_name [OK]
Common Mistakes:
  • Omitting ^ anchor in regex pattern
  • Thinking delimiters like / / are needed
  • Ignoring nginx error messages about regex
5. You want nginx to serve requests for any subdomain of example.com except www.example.com. Which server_name config achieves this?
hard
A. server_name ~^(?!www\.)[^.]+\.example\.com$;
B. server_name *.example.com www.example.com;
C. server_name ~^www\d+\.example\.com$;
D. server_name example.com *.example.com;

Solution

  1. Step 1: Understand the requirement

    We want to match any subdomain except 'www.example.com'. This requires a regex with negative lookahead.
  2. Step 2: Analyze options

    server_name ~^(?!www\.)[^.]+\.example\.com$; uses ~^(?!www\.)[^.]+\.example\.com$ which matches any subdomain not starting with 'www.'. Others either include 'www' or don't exclude it.
  3. Final Answer:

    server_name ~^(?!www\.)[^.]+\.example\.com$; -> Option A
  4. Quick Check:

    Negative lookahead excludes www subdomain [OK]
Hint: Use negative lookahead in regex to exclude specific subdomains [OK]
Common Mistakes:
  • Using wildcard that includes www.example.com
  • Not using regex for exclusion
  • Confusing wildcard and regex syntax
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard