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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github