Nginx: can I use $server_name when specifying access log location?

hwjp picture hwjp · May 27, 2013 · Viewed 11.4k times · Source

I want to write a config file for an nginx virtual host that looks like this:

server {
    listen 80;
    server_name www.my-domain-name.com;

    access_log /home/me/sites/$server_name/logs/access.log;
    error_log  /home/me/sites/$server_name/logs/error.log;

    location /static {
        alias /home/me/sites/$server_name/static;
    }

    location / {
        proxy_pass http://localhost:8000;
    }
}

Using $server_name seems to work find for the location /static, but it doesn't seem to work for the access_log and error_log -- am I doing something wrong? Or is this just not possible? Can I do it some other way?

[update] - this is the error message when trying to reload nginx:

nginx: [emerg] open() "/home/me/sites/$server_name/logs/error.log" failed (2: No such file or directory)

Answer

Malvineous picture Malvineous · Sep 21, 2013

I wanted to do this too, but apparently by design nginx cannot expand variables in the error_log command, in case there are errors doing so and it cannot get a log filename to write them to.

Their suggestion is to use some program to generate your configuration files instead. You could use sed for this, to automatically search-and-replace your own variables and placing the output in the nginx configuration directory.