Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx try_files (folders + files) fallback

Tags:

nginx

Given this folder structure:

root folder
    + default
        + settings1.txt
        + settings2.txt
        ...
        + settingsN.txt
    + user00001
        + settings1.txt
        ...
    ...
    + userN
        + settings1.txt
        ...

And this example url:

domain.com/user00009/settings1.txt

Or

domain.com/xavi/somefile.txt

I would like to write a rule that let me do:

folder exists ? check file : 404

file exists ? serve users file : serve default file

I tried using try_files but I think I can only use $uri i get the whole url, would be great if I could work with the slugs ( $1 = user00009 & $2 = settings1.txt )

Then maybe I could put:

location / {
   root /...
   try_files $1/$2 default/$2 =404;
}

Any idea?

Note: I know i could server the files from outside nginx ( in this case django ) but Im trying to speed things up

like image 231
Mc- Avatar asked Feb 15 '12 00:02

Mc-


1 Answers

location ~ ^(/[^/]+)(/.+)$ {
  root ...;
  if (!-d "$document_root$1") {
    return 404;
  }
  try_files $1$2 /default$2 =404;
}
like image 183
Alexander Azarov Avatar answered Oct 31 '22 15:10

Alexander Azarov