How i can use variables in nginx config to provide some paths for NGINX?

AccessDenied asked:

I want make dynamic subdomains with logs in separate directories, but have a problem with it:

  1. If i provide path to logs like /var/www/demo/subdomains/$sub/logs/access.log and same with error, NGINX writes /var/www/demo/subdomains/$sub/logs/error.log" failed (2: No such file or directory)
  2. If i provide path like in config now /var/www/demo/subdomains/logs/$sub-error.log i have problem what $sub-access.log named correctly like demo1-access.log or demo2-acces.log, but $sub-error.log named just as $sub-error.log. For 2 domains i have 3 files – demo1-access.log, demo2-access.log, and $sub-error.log

What changes i need to do for become 1 way become true? Second fine to, but not so beautiful.

server {
    listen 80;
    listen [::]:80;

    server_name "~^(?<sub>.+)\.deb\.test$";
    root /var/www/demo/subdomains/$sub/www;
    index index.php index.html;

    access_log /var/www/demo/subdomains/logs/$sub-access.log combined;
    error_log /var/www/demo/subdomains/logs/$sub-error.log info;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_param SCRIPT_FLIENAME [email protected]_script_name;
        include /etc/nginx/fastcgi.conf;

    location / {
        try_files $uri $uri/ /index.php?$args;

    location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ {
        return 403;
        error_page 403 /403_error.html;

    location ~* \.(ico|pdf|flv)$ {
        expires 1y;

    location ~* \.(js|css|png|jpg|jpeg|gif|swf|xml|txt)$ {
        expires 14d;

    location ~ /\.ht {
        deny all;

My answer:

It is possible to use variables (with some limitations) in the access_log directive, but it is not possible to use variables in the error_log directive. To log errors to a different file, you would need to use a different error_log directive, probably in a new server block.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.