What is the difference between HTTP_HOST
and SERVER_NAME
in PHP?
where:
HTTP_HOST
=== $_SERVER[\'HTTP_HOST\'
It took me a while to understand what people meant by 'SERVER_NAME
is more reliable'. I use a shared server and does not have access to virtual host directives. So, I use mod_rewrite in .htaccess
to map different HTTP_HOST
s to different directories. In that case, it is HTTP_HOST
that is meaningful.
The situation is similar if one uses name-based virtual hosts: the ServerName
directive within a virtual host simply says which hostname will be mapped to this virtual host. The bottom line is that, in both cases, the hostname provided by the client during the request (HTTP_HOST
), must be matched with a name within the server, which is itself mapped to a directory. Whether the mapping is done with virtual host directives or with htaccess mod_rewrite rules is secondary here. In these cases, HTTP_HOST
will be the same as SERVER_NAME
. I am glad that Apache is configured that way.
However, the situation is different with IP-based virtual hosts. In this case and only in this case, SERVER_NAME
and HTTP_HOST
can be different, because now the client selects the server by the IP, not by the name. Indeed, there might be special configurations where this is important.
So, starting from now, I will use SERVER_NAME
, just in case my code is ported in these special configurations.