?? Web servers match which website to serve based on the Host header.
— Chris Fidao (@fideloper) May 16, 2018
Often with a default.
Or, if no default is defined, whichever server config was loaded first. pic.twitter.com/cPIEYW57gJ
Since our web servers can be configured to serve multiple sites, one question we need to ask is "How does the web server know which site to serve?
Host Header
On the surface, all we see are:
- I put
foo.com
into my browser - I setup a web server configuration with something like
server_name foo.com
(Nginx) orServerName foo.com
(Apache).
What might be less obvious is that the web server is actually using the Host
header to grab the hostname and match against the configured Server Name.
In our browsers, the Host
header is set automatically by using whatever we put into the URL bar.
In a curl
request, no Host
header is set unless we manually define one:
# Will serve the default site
curl localhost
# Will serve site with server name "foo.com"
curl -H "Host: foo.com" localhost
Default Sites
When an HTTP request has no Host
header set, the web server needs to decide which site to server.
When there's no Host header, Nginx and Apache have slightly different behaviors when deciding which site to server.
In Apache, the first virtualhost configured will be the one that gets served. This is why we often see virtualhost configuration files numbered - so they're loaded into Apache in a specific order. The first one loaded (the first one we see on the file system in alphabetical order) will be the one used.
In Nginx, it will use which ever is marked as the default_server
for the port being used (typically either port 80 or 443). If there is no default_server
, then Nginx uses the first configuration that is loaded.