1

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 ~^(.+)$;
}
viniciussss
  • 185
  • 3
  • 8
  • 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? – Joe Sniderman Apr 11 '15 at 03:32
  • 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 – ben schwartz Apr 11 '15 at 15:44
  • Which value does Apache assign to SERVER_NAME when the HTTP request doesn't contain HTTP_HOST header? – Tero Kilkanen Apr 11 '15 at 23:23

1 Answers1

4

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';
}
Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63
  • 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. – viniciussss Apr 11 '15 at 21:22
  • 1
    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. – Tero Kilkanen Apr 11 '15 at 23:16