$server_name

The $server_name variable represents the name of the virtual host serving the request. — NGINX Core (HTTP)

$server_name NGINX Core (HTTP)

Description

The $server_name variable in NGINX is automatically populated with the name defined in the server block of the configuration. It can either match the Host header of an incoming request or be explicitly set in the server block. The value of $server_name varies depending on how the server block is defined; it can take multiple forms, including a single name, a wildcard, or a regular expression. If the request doesn't match any server blocks defined in the configuration, $server_name will be unset. This variable is typically used for logging, error pages, and rewrite directives, enabling the server to dynamically customize responses based on the requested host. When working with multiple server names for a single server block, NGINX will perform a simple matching process, prioritizing exact matches over wildcards or regular expressions. To utilize the $server_name variable effectively, it’s essential to configure the server block correctly and ensure that it aligns with the incoming requests. This variable can also be accessed in the logs to provide context about requests being processed, thus aiding in debugging and analytics.

Config Example

server {
    listen 80;
    server_name example.com www.example.com;

    location / {
        root /var/www/example;
        index index.html;
    }

    error_page 404 /404.html;
    access_log /var/log/nginx/example.access.log;
    error_log /var/log/nginx/example.error.log;
}

Subsystem

http

Cacheable

Yes

Contexts

http, server, location, if

If no matching server block is found for a request, $server_name will be unset, potentially leading to confusion in logs or redirects.

Avoid using $server_name in locations where it might be impacted by regex or wildcard definitions in server blocks, as results may vary.

Remember that the presence of www or subdomains needs to be accurately reflected in server_name to ensure correct behavior.