What is the difference between Nginx variables $host, $http_host, and $server_name?

Better Stack Team
Updated on November 23, 2023

In Nginx, the variables $host, $http_host, and $server_name serve different purposes and hold distinct values within the context of an HTTP request. Here's a breakdown of their differences:

$host:

  • The $host variable in Nginx represents the value of the Host header in the HTTP request. It contains the hostname provided by the client in the HTTP request.
  • It is derived from the Host header sent by the client and may not always represent the server's hostname. This header can be set by the client or by intermediary systems.

Example:

 
server {
    listen 80;
    server_name example.com;

    location / {
        echo $host;  # Will output the value of the Host header in the client's request
    }
}

$http_host:

  • The $http_host variable holds the value of the Host header sent by the client in an HTTP request.
  • It's specifically a part of the $http_ variable family in Nginx. It's the same as $host and holds the value of the Host header.

Example:

 
server {
    listen 80;
    server_name example.com;

    location / {
        echo $http_host;  # Will output the value of the Host header in the client's request
    }
}

$server_name:

  • The $server_name variable in Nginx holds the server name that matches the current request.
  • It's typically used to match the server block in the Nginx configuration based on the incoming request.

Example:

 
server {
    listen 80;
    server_name example.com;

    location / {
        echo $server_name;  # Will output the server name defined in the current server block
    }
}

Each of these variables holds the hostname or server name but may have different sources and contexts. While $host and $http_host typically represent the value of the Host header sent by the client, $server_name refers to the server name defined in the Nginx configuration for the current request. Understanding their differences can help in making proper use of these variables in your Nginx configuration.