I have a nested location directive, I want to serve the app at the /api and the static files in the /api/static/

For serving static files I'm using try_files $uri /dev/null =404 inside a nested location.

location /api/ {

        location /api/static/ {
            try_files $uri /dev/null =404;
            root /shared_volumes/staticfiles/;

        proxy_set_header        Host                    $host;
        proxy_set_header        X-Real-IP               $remote_addr;
        proxy_set_header        X-Forwarded-For         $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto       $scheme;
        proxy_pass              http://app:8000/api/;

but that doesn't work, nginx returns not found when accesing http://app/api/static/afile.css although the file exists in /shared_volumes/static/afile.css

In the NGINX docs $uri is

current URI in request, normalized The value of $uri may change during request processing, e.g. when doing internal redirects, or when using index files.

How does nginx $uri behave in nested location? Does nginx search file api/static/afile.css in /shared_volumes/staticfiles/ instead of afile.css?

  • 1
    The URI /api/static/afile.css will be looked for at /shared_volumes/staticfiles/api/static/afile.css. That's how root works. Perhaps you need to use alias instead. – Richard Smith Apr 8 '19 at 12:40
  • BTW, this try_files is meaningless. Even more, it will try file $root/dev/null, I doubt you've meant that – Alexey Ten Apr 8 '19 at 12:49

I changed the /api/static/ location directive as sugested by @Richard and @Alexey in the comment above

    location /api/static/ {
        alias /shared_volumes/staticfiles/;

and it now works, thanks!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.