What's the difference of $host and $http_host in Nginx

ConfigurationNginxHttp Headers

Configuration Problem Overview


In Nginx, what's the difference between variables $host and $http_host.

Configuration Solutions


Solution 1 - Configuration

$host is a variable of the Core module.

> $host

> This variable is equal to line Host in the header of request or > name of the server processing the request if the Host header is not > available.

> This variable may have a different value from $http_host in such > cases: 1) when the Host input header is absent or has an empty value, > $host equals to the value of server_name directive; 2)when the value > of Host contains port number, $host doesn't include that port number. > $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

> $http_HEADER

> The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Solution 2 - Configuration

The accepted answer and its comments don't seem to be correct (anymore). The docs (http://nginx.org/en/docs/http/ngx_http_core_module.html#var_host) say that $host is

> in this order of precedence: host name from the request line, or host name from the “Host” request header field, or the server name matching a request

So $http_host is always the value of the Host header field. They might differ if the host in the request line (if specified) differs from the Host header field. Or if the Host header is not set.

server_name matches only the Host header field (http://nginx.org/en/docs/http/request_processing.html), so that $host may differ from the matched server_name.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionglarrainView Question on Stackoverflow
Solution 1 - ConfigurationglarrainView Answer on Stackoverflow
Solution 2 - ConfigurationChristianView Answer on Stackoverflow