11

Based on the Nginx wiki the $hostname variable is set to the machine's hostname as returned by gethostname.

I tried that and although gethostname doesn't work my Debian box it still returns the host correctly. Then I tried to use that variable $hostname to set the server_name, but that didn't work.

Why is that and is there another way I can accomplish that?

server {
    listen   80;

    autoindex off;

    server_name  static.$hostname;
    root   /var/www/static;

    access_log  /var/log/nginx/localhost.access.log;

    location / {
        index  index.html;
    }

    error_page  404  /404.html;
    error_page  500 502 503 504  /50x.html;
}
RoboTamer
  • 502
  • 1
  • 4
  • 17

2 Answers2

9

Most variables in nginx only exist at runtime, not during configuration time.

For this reason, most variables cannot be used with the server_name directive. Since $hostname is a constant value, there's an explicit check for exactly $hostname in the server_name handler.

It only allows for the server_name to be set to $hostname, not static.$hostname. You may be able to patch the source to make it support that feature (ngx_http_core_module.c, look for $hostname), but you can't do it with the existing code.

kolbyjack
  • 8,039
  • 2
  • 36
  • 29
0

You should find this works:

server_name static.*;
rich
  • 158
  • 6
  • This would be incredibly insecure and allow host header injection attacks to anyone who sets "static.malicioushostnamehere.com" as an example. – MattBoothDev Nov 16 '18 at 11:25
  • I have worked with use cases where this is fine, but other use cases this is incredibly insecure. Know the risks. – 700 Software Apr 30 '21 at 20:11