Nginx try_files (folders + files) fallback

2019-02-22 05:47发布

问题:

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

回答1:

location ~ ^(/[^/]+)(/.+)$ {
  root ...;
  if (!-d "$document_root$1") {
    return 404;
  }
  try_files $1$2 /default$2 =404;
}


标签: nginx