Score:0

Nginx try_file directive not working as expected

zm flag

I am trying to understand the Nginx config file. Here is my app directory tree:

/app
|-- abcd.html
|-- file.php
|-- index.html
|-- index.php
|-- sss
|   `-- index.html
|-- style.css
`-- thumb.png

Here is my test nginx config:

events {}
http {
        rewrite_log on;
        error_log /var/log/nginx/localhost.error_log debug;
        server {
                include mime.types;
                root /app;
                listen 8080;
                index index.html;
                location / {
                        try_files $uri/  =404;
                }
        }
}

From my understanding of the Nginx config file, when I request for localhost:8080/, according to try_files documentation, it should check for file /, then because it is a directory, it should serve index file inside. But actually, it doesn't. I also tried try_files $uri =404;. It returns a 404 page, too. But when I try try_files $uri $uri/ =404, it works and it responds with index file. Can anyone please explain what is going on?

I also tried something else that didn't work as expected. As before, in the location context, I tried try_files /sss /sss/ =404. I expected it serves me the index file inside sss directory, no matter what my requested url is. But it gets stuck in an infinite loop of requests. It responds with a 301 redirection and requests for /sss/ url. isn't it like the previous case, when I used try_files $uri $uri/ =404?

Richard Smith avatar
jp flag
The [`index` module](http://nginx.org/en/docs/http/ngx_http_index_module.html#index) is responsible for processing URIs ending with a `/`. And it will cause an *internal redirect* which changes the value of `$uri` to `/index.html`. That is why you need *both* `$uri` and `$uri/` in the `try_files` statement.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.