Nginx – How to create dynamic root path in NGINX config

nginxregex

During my deployment, I create artifacts, which are folders with static files – html, css, js. And they are copied to the server in the folder /usr/share/nginx/html/${SHORT_COMMIT_HASH}.

The site, for example, is available by reference.

site.com/${SHORT_COMMIT_HASH} 

Requests look like this:

site.com/9f9b348b/some_url_1/1
site.com/9f9b348b/some_url_2/2

I need to, when entering any link starting site.com/${SHORT_COMMIT_HASH}, index.html from directory /usr/share/nginx/html/${SHORT_COMMIT_HASH} was displayed

I have nginx config for it:

server {
    listen       80;
    server_name  localhost;

    location / {
      root /usr/share/nginx/html;
    }

    location ~ ^/([a-zA-Z0-9]*)/ {
      root /usr/share/nginx/html;
      try_files $uri $uri/ /$1/index.html;
    }
}

But I have a trouble. css, js files nginx try to find not in site.com/${SHORT_COMMIT_HASH}, but in a root of site.com/

How can I change root for location / where for every request, woul be own root, relative ${SHORT_COMMIT_HASH};

How I can with variables do this:

location / {
  root /usr/share/nginx/html/${SHORT_COMMIT_HASH};
} 

Best Answer

I find solution with sub_filter:

server {
    listen       80;
    server_name  localhost;

    location / {
     root /usr/share/nginx/html;
     try_files $uri $uri/ /$1/index.html;

     location ~ "^/([a-z0-9]{8})/" {
        try_files $uri /$1/index.html = 404;
        sub_filter_once off;
        # sub_filter_types text/html; # mime-type based rewriter
        sub_filter '/static' '/$1/static';
  }
    }

    location ~ ^/([a-zA-Z0-9]*)/ {
      root /usr/share/nginx/html;
      try_files $uri $uri/ /$1/index.html;
    }
}