Why is this nginx rewrite apparently duplicating pre-existing configuration?

mechdeveloper asked:

I am new to nginx, I have read some of the documentation at wiki.nginx.org, as long as I know the try_files sentence will do exactly as it says, it will search a file in the order given, as I see this sentence is used extensively along with the $uri variable (which has the requested uri), however, nginx is not accessing the directories without the trailing slash even using the try_files sentence as this:

try_files $uri $uri/ =404;

if I am understanding well, if I look for this:, it will not find anything at the begining but it should find the directory at second (unless the index file is not being checked), but that is not happening, looking for a solution for this I have found this quetion add-slash-to-the-end-of-every-url-need-rewrite-rule-for-nginx, one of the answers suggested to apply this rewrite sentence in order to make the directories be accessed without a trailing slash (something that it worked):

rewrite ^([^.]*[^/])$ $1/ permanent;

my question is: is not the try_files sentence doing that already? (it has sense to me but it does not work as I think, I checked the access.log file in order to find a logic answer but I could not figure out this).

My answer:

The $uri/ in try_files does not exactly add a / to the end of the URL and try it. Instead, when the parameter ends with a / the request is passed on to an index module, depending on whether you have specified the index, autoindex or random_index directives in your server or location blocks.

Thus, if you had specified:

index index.php;


try_files $uri $uri/ =404;

will look for index.php in that corresponding directory, when given a URL ending in /. If you used autoindex instead, then nginx would generate a directory listing for that directory.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.