How does try_files work?

try_files tries the literal path you specify in relation to the defined root directive and sets the internal file pointer. If you use for instance try_files /app/cache/ $uri @fallback; with index index.php index.html; then it will test the paths in this order:

  1. $document_root/app/cache/index.php
  2. $document_root/app/cache/index.html
  3. $document_root$uri

before finally internally redirecting to the @fallback named location. You can also use a file or a status code (=404) as your last parameter but if using a file it must exist.

You should note that try_files itself will not issue an internal redirect for anything but the last parameter. Meaning you cannot do the following: try_files $uri /cache.php @fallback; as that will cause nginx to set the internal file pointer to $document_root/cache.php and serve it, but since no internal redirect takes place the locations aren’t re-evaluated and as such it will be served as plain text. (The reason it works with PHP files as the index is that the index directive will issue an internal redirect)

Leave a Comment