$hostname
The $hostname variable returns the hostname of the server as specified in the server block. — NGINX Core (HTTP)
Description
The $hostname variable is set during the processing of a request and reflects the server's hostname as defined in the NGINX configuration. It pulls the value from the 'server_name' directive if specified, otherwise it defaults to the hostname of the server's operating system. This variable is particularly useful for applications that need to know the name of the host that is serving the requests, facilitating configurations that depend on the server's identity. NGINX evaluates the $hostname variable at the request stage, meaning it can be utilized in various contexts such as logging, redirects, or condition-based server routing. It generates values based on the server block where the request is processed—allowing for dynamic configurations if multiple server blocks with different names are defined. If a 'server_name' is not specified, NGINX will fall back to using the system's hostname, which can be confirmed via the command line using the 'hostname' command on Linux systems. To set this variable effectively, it is best practice to define the 'server_name' directive in your server blocks to ensure consistent behavior, especially in environments with multiple hostnames or virtual hosts. This approach alleviates ambiguity and ensures that the application utilizes the correct domain name associated with received requests.
Config Example
server {
listen 80;
server_name example.com;
location / {
add_header X-Host $hostname;
}
}Subsystem
httpCacheable
YesContexts
http, server, location, ifIf no 'server_name' is specified, it defaults to the system's hostname, which can lead to unexpected values in multi-host configurations.
Modifications to the system's hostname do not translate to changes in the NGINX configuration until NGINX is restarted, which may lead to inconsistency during runtime.