SERVER_NAME vs HTTP_HOST (Nginx + PHP)

5,767

I would approach this issue like this in your PHP code:

if (isset($_SERVER['HTTP_HOST'])) {
    $host = $_SERVER['HTTP_HOST'];
} else {
    $host = 'default.example.com';
}
Share:
5,767

Related videos on Youtube

viniciussss
Author by

viniciussss

Updated on September 18, 2022

Comments

  • viniciussss
    viniciussss almost 2 years

    I have a catchall server configuration that gets all sub-domains and point them to the same PHP script. There are thousands of sub-domains and they are created dynamically.

    The PHP script uses the HTTP_HOST to identify the sub-domain and fetch the content from the database accordingly to the sub-domain identified.

    It works fine, but I am receiving this log from Nginx:

    PHP message: PHP Notice:  Undefined index: HTTP_HOST in
    /usr/share/nginx/html/index.php on line 9
    

    I've searched the web and found out that HTTP_HOST may not always be set. The PHP manual says:

    'HTTP_HOST' = Contents of the Host: header from the current request, if there is one.

    So I thought about using the variable SERVER_NAME instead of HTTP_HOST. But when I do it, SERVER_NAME does not contain the sub-domain part. It will always return what I write in the Nginx config, that is ~^(.+)$ in my case.

    Is there a way to change Nginx config so that SERVER_NAME include the dynamic sub-domains? For example, to return something like sub1.mydomain.com, sub2.mydomain.com and so on.

    Is there any solution for this problem?

    My actual configuration is:

    server {
        listen 80 default_server;
        server_name ~^(.+)$;
    }
    
    • Joe Sniderman
      Joe Sniderman about 9 years
      What exactly do you have in index.php on line 9? If you could edit your question to include your php code, that might help folks pinpoint the problem?
    • ben schwartz
      ben schwartz about 9 years
      SERVER_NAME works the way you're expecting in apache, so I think you're on the right path getting nginx to pass this through
    • Tero Kilkanen
      Tero Kilkanen about 9 years
      Which value does Apache assign to SERVER_NAME when the HTTP request doesn't contain HTTP_HOST header?
  • viniciussss
    viniciussss about 9 years
    But I need to know the subdomain from the URL the user entered to decide what content to show. If the user entered the URL sub1.example.com I need to show some content, but if the user entered the URL sub2.example.com I need to show a different content. There is not a default content.
  • Tero Kilkanen
    Tero Kilkanen about 9 years
    The subdomain comes to the web server only if the software making the HTTP requests sends the HTTP_HOST header to the server. If there are user agents that simply do only a DNS lookup for IP address and do not send a HTTP_HOST header, you cannot find out what subdomain those users want. Maybe you want to then display an error message to those that you don't support their user agents.