12

I have an nginx server definition with a regex match, like this:

server_name ~^(?<vhost>[a-z0-9-]+)\.example\.com$;
root /var/www/example/$vhost;
access_log /var/log/nginx/$vhost.example-access.log;

That all works nicely, however, this domain hosts various PHP projects using fastcgi and PHP-FPM, which receive values like this in $_SERVER:

SERVER_NAME => "~^(?<vhost>[a-z0-9-]+)\.example\.com$"
HTTP_HOST   => "myhost.example.com"

As you can see, the regex pattern is put into SERVER_NAME rather than the string that it matched. That seems a bit buggy to me, and also represents a security risk in that it is revealing unnecessary details (in other configs I'm matching a specfic set of names rather than a wildcard).

You might say "use HTTP_HOST instead of SERVER_NAME" - if only it was that simple - there are libraries which expect SERVER_NAME to (no surprise) contain the name of the server. I can't really see a good use case for this behaviour.

2 Answers 2

14

Thanks to the rubber-duck effect of writing this question, I found a solution.

Nginx's stock fastcgi_params file contains the line:

fastcgi_param  SERVER_NAME        $server_name;

which is what causes that value to appear in $_SERVER['SERVER_NAME'] in the PHP environment.

I changed that to use the $host variable:

fastcgi_param  SERVER_NAME        $host;

and my problem went away. I'd be interested to know if there are any downsides of this approach.

1
  • The only downside to this approach is as it's relying on $host variable, which means it can be overwritten by user if he sends HTTP_HOST header. You can test this using curl: curl --header "HOST: google.com" http://yourdomain/yourpage.php and in yourpage.php put: <?php echo $_SERVER['SERVER_NAME']; ?> You will see google.com
    – Ghulam Ali
    Nov 8, 2018 at 11:15
2
server_name  ~^(?<subdomain>.+)\.example\.com$;
set $server_name_full $subdomain.example.com;


location ~ \.php$ {
    ...
    include fastcgi_params;
    fastcgi_param SERVER_NAME $server_name_full;
    ...
}
1
  • 3
    Although the code is appreciated, it should always have an accompanying explanation. This doesn't have to be long, but it is expected.
    – peterh
    Nov 17, 2015 at 11:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .