In Nginx, what's the difference between variables $host
and $http_host
.
2 Answers
$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 theHTTP_HOST
request header.$host
equals$http_host
, lowercase and without the port number (if present), except whenHTTP_HOST
is absent or is an empty value. In that case,$host
equals the value of theserver_name
directive of the server which processed the request.
-
73$host is specifically the first
server_name
that is defined in the current server block. if you have multipleserver_name
s, only the first one will appear. Mar 14, 2013 at 16:36 -
5True. In fact, it is quite typical to define: server_name example.com www.example.com;– glarrainMar 14, 2013 at 16:41
-
6Does the
$server_name
variable equal theserver_name
directive's value or the actual server name that was selected if there were multipleserver_name
directives? Mar 13, 2014 at 20:03 -
2@CMCDragonkai
$server_name
is always equal to the first value specified with the server_name directive. For example, withserver_name example.com one.example.com two.example.com;
,$server_name
will always be "example.com", regardless of which host the user has specified. In fact, if you don't have adefault_server
, the host might be something completely different (like example.org).– ATLiefApr 2, 2019 at 14:23 -
2
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
.