0
0
NginxConceptBeginner · 3 min read

What is server_name in nginx: Explanation and Usage

In nginx, server_name specifies the domain names or IP addresses that a server block should respond to. It tells nginx which website or hostname to match when processing incoming requests.
⚙️

How It Works

The server_name directive in nginx acts like a receptionist who decides which website to serve based on the name the visitor types in their browser. When a request comes in, nginx looks at the Host header in the request and compares it to the server_name values defined in its configuration.

If it finds a match, nginx uses that server block to handle the request. If no match is found, it uses the default server block. This is similar to how a phone operator routes calls to the right department based on the number dialed.

💻

Example

This example shows a simple nginx server block that responds to requests for example.com and www.example.com.
nginx
server {
    listen 80;
    server_name example.com www.example.com;

    location / {
        root /var/www/html;
        index index.html;
    }
}
Output
When a user visits http://example.com or http://www.example.com, nginx serves files from /var/www/html.
🎯

When to Use

Use server_name to specify which domain names your nginx server should respond to. This is essential when hosting multiple websites on the same server (called virtual hosting).

For example, if you host example.com and myblog.com on one server, you create separate server blocks with different server_name values to serve each site correctly.

It also helps nginx decide which SSL certificate to use when serving HTTPS sites with different domain names.

Key Points

  • server_name matches the domain or hostname in the request.
  • It enables hosting multiple sites on one server.
  • Supports exact names, wildcards, and regular expressions.
  • Helps nginx select the right server block and SSL certificate.

Key Takeaways

server_name tells nginx which domain names to respond to.
It is essential for hosting multiple websites on one server.
You can use exact names, wildcards, or regex in server_name.
If no match is found, nginx uses the default server block.
Proper server_name setup ensures correct site delivery and SSL handling.