Nginx – Wildcard subdirectory in nginx location block

nginx

I have the following working vhost configuration:

server {
listen       443 ssl http2;
server_name  example.com;
root  /home/sites/example.com/html; #main dir for main site domain
index index.php index.html index.htm;

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

}

Then I want to have subsite with this structure example.com/sub1, but for the sack of being organized, I don't want the sub1 to be in /home/sites/example.com/html. I'd rather it to be in /home/sites/example.com/subsites. So I add this location block, and it works

location /sub1/ {
  root  /home/sites/example.com/subsites;
  ....
}

The problem here is that if I want to create another subsite, I have to copy this block and change a little bit. For example, for sub2, I will have to make a directory name sub2 in /home/sites/example.com/subsites then add a location block like this:

location /sub2/ {
   root  /home/sites/example.com/subsites;
    ....
}

and I can access it via example.com/sub2

I want to make a location with regex matching, so that everytime I make a directory in /home/sites/example.com/subsites (dir3, dir4, dir5,… dirN) so that those newly created dirs will be accessible via example.com/dir3, example.com/dir4, example.com/dir5,…example.com/dirN
I've tried with this block, nginx restart fine, but I can't access the newly created dirs, and only get 404 error

location ~* "/dir([0-9]{1,4})/" {
root  /home/sites/example.com/subsites;
}

Best Answer

This is a weird problem, I guess. In my .conf file there are these blocks:

location ~* /\.well-known {
    allow all;
}

location ~* /\. {
    deny all;
}

location ~* /(?:uploads|files)/.*\.php$ {
    deny all;
}

location ~* \.(jpg|jpeg|gif|png|css|js|swf|ico|pdf|svg|eot|ttf|woff)$ {
    expires 60d;
    access_log off;
}

When I put this block after those block, and access example.com/dir3 (after making a directory dir3 in /home/sites/example.com/subsites, it show 404 page.

location ~* "/dir([0-9]{1,4})/" {
root  /home/sites/example.com/subsites;
}

The problem is solved by moving this block above those blocks. I don't know the reason behind, but the problem is solved, anyway.