What is server_name in nginx: Explanation and Usage
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
example.com and www.example.com.server {
listen 80;
server_name example.com www.example.com;
location / {
root /var/www/html;
index index.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_namematches 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.server_name.server_name setup ensures correct site delivery and SSL handling.