$host
The $host variable in NGINX holds the host name from the HTTP request header or the server name defined in the configuration. — NGINX Core (HTTP)
Description
The $host variable is crucial for handling incoming requests, as it directly extracts the host name from either the Host request header or the appropriate server name defined in the NGINX configuration. When a request comes in, NGINX checks the Host header; if it is present, the value of this header is used to set the $host variable. If the header is absent, NGINX falls back to using the server name configured in the server block that handled the request. This behavior allows NGINX to respond appropriately to requests made to different domains or subdomains that point to the same server instance. This variable is typically assigned values that correspond to the domain names or IP addresses being accessed by clients. For example, if a user requests "http://example.com/path", the $host variable will contain "example.com". If the request does not specify a hostname and the server block has a default server defined, $host would hold that server's name. It's important to note that if NGINX is configured with multiple server blocks for different hostnames, the value of $host can be critical for routing requests to the correct block based on the incoming URL. The $host variable can also behave differently depending on the presence of the server_name directive. If the configured server names for a server block include wildcards or regex, the actual value of $host might be influenced by the specific match found during the request handling process. This ensures that requests are served correctly based on specific hostnames, enabling multi-tenancy configurations on a single NGINX server instance.
Config Example
server {
listen 80;
server_name example.com;
location / {
return 200 "Host is: $host";
}
}Subsystem
httpCacheable
YesContexts
http, server, location, ifIf the Host header is not sent by the client, the $host variable may not behave as expected, potentially affecting routing.
Ensure that the server block with the desired server_name is configured correctly, otherwise you might get unexpected values for $host.