Nginx rewrite location internally to serve static content

nginxroutingstatic-contentstatic-routesUbuntu

I'm trying to serve static content from an endpoint that differs in hierarchy structure than the actual root directory structure. This is the result I'm trying to achieve:

0.0.0.0/Claw/scripts/main.js -> /home/ubuntu/Claw/public/scripts/main.js

I'm using the following Nginx configuration:

location ~ ^/Claw/(images/|styles/|scripts/) {
    root /home/ubuntu/Claw/public;
    access_log off;
    expires max;
}

This is failing as /home/ubuntu/Claw/public/Claw/scripts/main.js doesn't exist. Therefore I need to remove the prefixed Claw from the location internally. How can I go about doing this?

I want this structure so I can host multiple Node apps from different endpoints on the same domain.

Best Answer

Try this:

location ~ ^/Claw/(?<subdir>images|styles|scripts)/(?<file>.*) {
    alias /home/ubuntu/Claw/public/$subdir/$file;
    access_log off;
    expires max;
}

It seems that nginx doesn't pass variables captured into numbered variables from location directive to inside the block. When the variables are given names, then they work.