8

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 Answer 1

10
location ~ ^(/[^/]+)(/.+)$ {
  root ...;
  if (!-d "$document_root$1") {
    return 404;
  }
  try_files $1$2 /default$2 =404;
}
7
  • Thanks @Alexander, I know this may be regex related, but what if the folder and file names are not named with patterns? instead of user0001:alexanderazarov and instead of settings1.txt:finance.txt?
    – Mc-
    Feb 15, 2012 at 9:19
  • Seems this line: if (! -d $document_root$1) { Is giving me an error :S
    – Mc-
    Feb 15, 2012 at 9:44
  • Is there a problem to make regex less specific? Please see my edits. I've wrapped the condtion's argument into double quotes as well, but frankly I'm not sure nginx allows $document_root in this context. You better try these edits, but probably you'll have to write /var/root$1 instead Feb 15, 2012 at 14:29
  • Partially working, I had to remove the space between ! and -d ( before: !_-d now: !-d ) in the first condition and add a ";" after the =404. try_files is not working... Is there any chance I can see what nginx is doing? (step by step) looks it cannot reach the folders... maybe $1 and $2 are wrong? do they need slash? $1/$2/
    – Mc-
    Feb 15, 2012 at 15:58
  • 1
    Thanks! I've fixed the answer. No, you don't need slashes, because regexp captures them. My recommendation is to keep error_log level at least at notice. And if you set error_log severity to debug, Nginx will write a lot of debugging information per every request. Feb 15, 2012 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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