1

I can't get my head round why my nginx config keeps looking for files in the wrong directory.

I'm trying to map the /files location to /home/user/toto. For that I'm using a regex capture group to remove the /files prefix and search for the files in the directory specified in the root directive.

 server { listen 80; server_name localhost; location ~^\/files\/(.*)$ { root /home/user/toto; try_files /$1/ /$1 ; autoindex off; } } 

The problem is I only get 404s. And that's pretty normal because here is what we can find in error.log :

2022/07/17 11:27:49 [error] 40358#0: *40 open() "/usr/local/nginx/html/test.txt" failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: "GET /files/test.txt HTTP/1.1", host: "localhost" 

As we can see the root directive seems to be completely ignored.

I tried an alternative configuration such as :

 server { listen 80; server_name localhost; location ~^\/files\/(.*)$ { # root /home/user/toto; try_files /home/user/toto/$1/ /home/user/toto/$1 ; autoindex off; } } 

But the problem is still the same. The only change is that the path now appears in the logs as a prefix for the file name :

2022/07/17 11:12:02 [error] 40288#0: *36 open() "/usr/local/nginx/html/home/user/toto/test.txt" failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: "GET /files/test.txt HTTP/1.1", host: "localhost" 

What am I missing ?

1 Answer 1

1

Your missing the last parameter from the try_files directive, so that the /$1 is being interpreted as an internal redirect instead of a file term.

Use:

try_files /$1/ /$1 =404; 

See this document for details.

Sign up to request clarification or add additional context in comments.

1 Comment

Right ; I knew that the last argument could become a rewrite but I thought it would still match files if there were some. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.