What is the main role of the server_name directive in an Nginx server block?
Think about how Nginx decides which server block handles a request based on the requested domain.
The server_name directive tells Nginx which domain names or IP addresses a server block should respond to. This helps Nginx route requests to the correct configuration.
Given this Nginx server block snippet:
server {
listen 80;
server_name example.com www.example.com api.example.com;
return 200 'Hello from example.com!';
}What will be the response when a user visits http://api.example.com?
Check which server_name matches the requested domain.
The server_name directive lists multiple names. Since api.example.com is included, Nginx matches it and returns the configured response.
Which server_name directive correctly matches all subdomains of example.com except the root domain itself?
Remember how wildcards work in domain matching for Nginx.
The *.example.com syntax matches all subdomains like www.example.com or api.example.com, but not example.com itself.
An Nginx server block has server_name www.example.com; but requests to example.com return 404 errors. What is the most likely cause?
Check if the requested domain is listed in server_name.
Since example.com is not in the server_name directive, Nginx does not route requests for it to this server block, causing 404 errors.
Given these server blocks, which server block will handle a request to test.example.com?
server {
listen 80;
server_name example.com;
return 200 'Root domain';
}
server {
listen 80;
server_name *.example.com;
return 200 'Wildcard subdomain';
}
server {
listen 80;
server_name test.example.com;
return 200 'Specific subdomain';
}Check how Nginx prioritizes exact names over wildcards.
Nginx matches exact server_name values before wildcard patterns, so the block with test.example.com handles the request.