0
0
Nginxdevops~15 mins

server_name directive in Nginx - Deep Dive

Choose your learning style9 modes available
Overview - server_name directive
What is it?
The server_name directive in nginx tells the server which domain names or hostnames it should respond to. It helps nginx decide which website configuration to use when multiple sites are hosted on the same server. You list one or more names, like example.com or www.example.com, and nginx matches incoming requests to these names. This way, nginx knows which content to serve based on the requested domain.
Why it matters
Without the server_name directive, nginx wouldn't know which website to show when multiple sites share the same server. This would cause confusion and wrong content delivery, making websites unreliable or inaccessible. It solves the problem of hosting many websites on one server by directing traffic correctly based on the domain name visitors use.
Where it fits
Before learning server_name, you should understand basic nginx configuration and how web servers handle requests. After mastering server_name, you can explore advanced nginx features like SSL setup, reverse proxying, and load balancing, which also rely on correctly identifying the requested domain.
Mental Model
Core Idea
The server_name directive tells nginx which website to serve by matching the domain name visitors use.
Think of it like...
It's like a receptionist at a building who directs visitors to the right office based on the company name they say at the door.
┌─────────────────────────────┐
│        Incoming Request      │
│  (with domain name in URL)  │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│        nginx Server          │
│  Checks server_name entries  │
│  to find matching website    │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│   Serve content for matched  │
│        domain name           │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is server_name directive
🤔
Concept: Introduce the basic purpose of server_name in nginx configuration.
The server_name directive is used inside a server block in nginx configuration. It lists domain names that the server block should respond to. For example: server { listen 80; server_name example.com www.example.com; root /var/www/example; } This means nginx will serve this site when the request is for example.com or www.example.com.
Result
Nginx knows which site to serve based on the domain name in the request.
Understanding server_name is key to hosting multiple websites on one server because it directs traffic correctly.
2
FoundationHow nginx matches server_name
🤔
Concept: Explain how nginx compares the requested domain to server_name values.
When a request arrives, nginx looks at the Host header in the HTTP request. It compares this to the server_name values in each server block. If it finds a match, it uses that server block to serve the request. If no match is found, nginx uses the default server block.
Result
Requests are routed to the correct website based on domain name matching.
Knowing nginx uses the Host header to match server_name helps understand why domain names must be correct.
3
IntermediateUsing wildcards in server_name
🤔Before reading on: do you think wildcards in server_name match any part of the domain or only specific parts? Commit to your answer.
Concept: Introduce wildcard patterns to match multiple domains with one rule.
You can use wildcards like *.example.com to match any subdomain of example.com. For example: server_name *.example.com; This matches blog.example.com, shop.example.com, but not example.com itself. You can also use prefixes like www.*.com but this is less common.
Result
One server block can handle many subdomains without listing each explicitly.
Wildcards simplify configuration when many similar domains need the same handling.
4
IntermediateUsing regular expressions in server_name
🤔Before reading on: do you think regex server_name matches are faster or slower than exact matches? Commit to your answer.
Concept: Show how to use regex patterns for flexible domain matching.
You can prefix server_name with ~ to use regular expressions. For example: server_name ~^www\.(.+)\.com$; This matches domains like www.test.com or www.site.com. Regex allows complex matching but is slower than exact or wildcard matches.
Result
You can match complex domain patterns with regex but at a performance cost.
Understanding regex matching helps balance flexibility and performance in nginx.
5
IntermediateDefault server and server_name fallback
🤔
Concept: Explain what happens when no server_name matches the request.
If no server_name matches the Host header, nginx uses the default server block for that port. You can set a default server by adding 'default_server' to the listen directive: server { listen 80 default_server; server_name _; root /var/www/default; } This catches unmatched requests.
Result
Requests with unknown domains still get a response, avoiding errors.
Knowing about default servers prevents unexpected 404 errors for unknown domains.
6
AdvancedPriority and order of server_name matching
🤔Before reading on: do you think nginx matches server_name in the order they appear or by specificity? Commit to your answer.
Concept: Explain nginx's matching priority rules for server_name directives.
Nginx matches server_name in this order: 1. Exact names (like example.com) 2. Longest wildcard starting with * (like *.example.com) 3. Longest wildcard ending with * (like www.*) 4. Regular expressions The first match found in this order is used. This means exact matches have highest priority.
Result
Requests are routed predictably even with overlapping server_name rules.
Understanding matching priority helps avoid conflicts and unexpected routing.
7
ExpertImpact of server_name on SSL and HTTP/2
🤔Before reading on: do you think server_name affects SSL certificate selection? Commit to your answer.
Concept: Show how server_name interacts with SSL and HTTP/2 protocols in nginx.
For HTTPS, nginx uses server_name to select the correct SSL certificate via SNI (Server Name Indication). If server_name is wrong or missing, the wrong certificate may be served, causing browser warnings. Also, HTTP/2 requires proper server_name matching to enable multiplexing and performance benefits.
Result
Correct server_name ensures secure and efficient HTTPS connections.
Knowing server_name's role in SSL prevents security issues and improves user experience.
Under the Hood
When nginx receives a request, it reads the Host header from the HTTP request. It then compares this header against all server_name directives in server blocks listening on the request's port. It uses a fast internal lookup optimized for exact and wildcard matches, falling back to regex if needed. Once a match is found, nginx uses that server block's configuration to process the request, including root paths, proxy settings, and SSL certificates.
Why designed this way?
The server_name directive was designed to allow one nginx instance to host many websites on the same IP and port. Before this, servers could only serve one site per IP:port. Using the Host header and server_name allows virtual hosting, saving IP addresses and simplifying hosting. The matching order balances speed (exact matches first) and flexibility (wildcards and regex last).
┌───────────────┐
│ Incoming HTTP │
│   Request     │
│ Host: domain  │
└───────┬───────┘
        │
        ▼
┌─────────────────────────────┐
│ nginx server block list      │
│ ┌─────────────────────────┐ │
│ │ server_name example.com  │ │
│ │ server_name *.example.com│ │
│ │ server_name ~^www\..+$  │ │
│ └─────────────────────────┘ │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Match found?                │
│ Yes → use matched server    │
│ No → use default server     │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Serve content and SSL cert  │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does server_name control which IP address nginx listens on? Commit yes or no.
Common Belief:Server_name controls the IP address nginx listens on.
Tap to reveal reality
Reality:Server_name only matches domain names in requests; IP addresses are controlled by the listen directive.
Why it matters:Confusing server_name with listen can cause misconfiguration where nginx doesn't respond on expected IPs.
Quick: Do you think a wildcard server_name like *.example.com matches example.com itself? Commit yes or no.
Common Belief:A wildcard like *.example.com matches example.com and all subdomains.
Tap to reveal reality
Reality:*.example.com matches only subdomains like blog.example.com, not example.com itself.
Why it matters:Assuming wildcards match the root domain can cause requests to example.com to go to the wrong server block.
Quick: Does nginx check server_name before or after SSL handshake? Commit your answer.
Common Belief:Nginx checks server_name after the SSL handshake completes.
Tap to reveal reality
Reality:Nginx uses SNI during the SSL handshake to select the certificate based on server_name before full connection is established.
Why it matters:Misunderstanding this can lead to SSL certificate mismatches and browser security warnings.
Quick: Are regex server_name matches faster than exact matches? Commit yes or no.
Common Belief:Regex server_name matches are as fast as exact matches.
Tap to reveal reality
Reality:Regex matches are slower and checked last after exact and wildcard matches.
Why it matters:Using regex unnecessarily can degrade server performance under high load.
Expert Zone
1
Nginx caches server_name lookups internally for speed, so changes require reload to take effect.
2
Using '_' as a server_name is a convention for a catch-all default server but is not a wildcard.
3
Regex server_name patterns can overlap and cause unexpected matches if not carefully ordered.
When NOT to use
Avoid using regex server_name unless necessary; prefer exact or wildcard matches for performance. If you need to route by IP or port, use the listen directive instead. For complex routing beyond domain names, consider using map or rewrite directives.
Production Patterns
In production, server_name is used with SSL certificates and HTTP/2 to serve multiple secure sites on one server. Wildcards are common for subdomain handling, and default_server blocks catch unknown domains. Regex is rare but useful for multi-tenant platforms with dynamic domains.
Connections
DNS (Domain Name System)
server_name depends on DNS to resolve domain names to server IPs
Understanding DNS helps grasp why server_name matches domain names and how requests reach nginx.
TLS SNI (Server Name Indication)
server_name works with SNI to select SSL certificates during HTTPS handshake
Knowing SNI clarifies how nginx serves the right certificate for multiple domains on one IP.
Virtual Hosting in Web Servers
server_name is nginx's method for name-based virtual hosting
Recognizing virtual hosting concepts helps understand why server_name is essential for hosting many sites on one server.
Common Pitfalls
#1Using server_name with incorrect domain spelling
Wrong approach:server_name exmple.com www.exmple.com;
Correct approach:server_name example.com www.example.com;
Root cause:Typos in domain names cause nginx to never match requests, leading to wrong site or default server responses.
#2Using wildcard server_name expecting it to match root domain
Wrong approach:server_name *.example.com;
Correct approach:server_name example.com *.example.com;
Root cause:Wildcards do not match the root domain, so it must be listed explicitly.
#3Not setting a default_server for unmatched requests
Wrong approach:server { listen 80; server_name example.com; root /var/www/example; } # No default server block
Correct approach:server { listen 80 default_server; server_name _; root /var/www/default; }
Root cause:Without a default server, unmatched requests may get errors or unexpected content.
Key Takeaways
The server_name directive tells nginx which domain names a server block should respond to, enabling hosting multiple sites on one server.
Nginx matches server_name using exact names first, then wildcards, and finally regular expressions, ensuring predictable routing.
Wildcards in server_name match subdomains but not the root domain, so both must be listed if needed.
Server_name works closely with SSL SNI to serve the correct certificate for HTTPS connections.
Setting a default server block ensures requests with unknown domains still receive a response, avoiding errors.