Why virtual hosting serves multiple domains in Nginx - Performance Analysis
We want to understand how nginx handles multiple websites using virtual hosting.
Specifically, how the work grows when more domains are added.
Analyze the time complexity of this nginx virtual hosting setup.
server {
listen 80;
server_name example.com;
root /var/www/example;
}
server {
listen 80;
server_name example.org;
root /var/www/example_org;
}
server {
listen 80;
server_name example.net;
root /var/www/example_net;
}
This config serves three different domains by matching the requested domain name.
When a request comes, nginx checks each server block to find a matching domain.
- Primary operation: Comparing the requested domain to each server_name.
- How many times: Once per server block until a match is found or all checked.
As the number of domains (server blocks) increases, nginx checks more names.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 comparisons |
| 100 | Up to 100 comparisons |
| 1000 | Up to 1000 comparisons |
Pattern observation: The work grows roughly in direct proportion to the number of domains.
Time Complexity: O(n)
This means the time to find the right domain grows linearly as more domains are added.
[X] Wrong: "nginx instantly knows the right domain no matter how many there are."
[OK] Correct: nginx checks domains one by one until it finds a match, so more domains mean more checks.
Understanding how nginx matches domains helps you explain real server behavior clearly and confidently.
"What if nginx used a hash map to find domains instead of checking each one? How would the time complexity change?"