Nginx regex vhost pattern ends up as PHP server name

nginx

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.

Best Answer

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.