Nginx · The edge of your stack
What is a server block and how does Nginx choose one?
Short answer
A server block is a virtual host defined by listen and server_name. Nginx picks the listener, then matches server_name exactly, by wildcard or regex, and falls back to the default server.
One Nginx instance can host many domains. The listen directive decides the address and port, and server_name decides which host gets the request. A default server handles requests whose Host header matches nothing.
server {
listen 80 default_server;
server_name _;
return 444;
}
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example;
index index.html;
}server_name matching order
- Exact names match first
- Longest wildcard starting with a star, such as *.example.com
- Longest wildcard ending with a star, such as www.example.*
- First matching regular expression in config order
- Otherwise the default_server for that listen address is used
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens when no server_name matches the Host header?
- 2Can two server blocks listen on the same address and port?
- 3What is the difference between default_server and server_name _?
- 4How do SNI and server_name interact for HTTPS?
Say it in the interview
A server block is a virtual host. I use listen to choose the address and port and server_name to match the Host header. Nginx tries exact names, then wildcards, then regexes, and finally the default server for that listener. I usually add a default server that rejects unknown hosts, and for HTTPS I remember that certificate selection uses SNI before the HTTP request is parsed.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Nginx mock interview and get scored feedback on depth, clarity and confidence.