using nginx try_files and autoindex together

Tyilo asked:

I have the following server configuration:

server {
    listen 80;
    server_name _;

    root /var/www/;

    location /calendars/ {
        autoindex on;
        try_files $uri.ics $uri =404;

If would expect to get the autoindex page on visiting, however I get an 404 File not found error instead.

I want the server do something like this pseudo-code:

if($uri is directory) {
    if(one of index pages exists in directory) {
        show index page;
    } else {
        show autoindex page;
} else {
    if($uri.ics exists) {
        show $uri.ics;
    } else if($uri exists) {
        show $uri;
    } else {
        show 404 page;

My answer:

You also need a check for the directory in try_files if you want the directory index loaded or autogenerated.

try_files $uri.ics $uri $uri/ =404;

Per the documentation for the try_files directive:

It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. $uri/

In other words, $uri means “try a file at the given path”, whereas $uri/ means “try a directory at the given path”, and the latter is what causes auto-indexing of that directory to kick in.

View the full question and any other answers on Server Fault.

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