Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: When the `index` and `try_files` in the same block, why the `try_files` will be processed, not the `index` directive?

Tags:

nginx

The nginx.conf is as following:

http {
    server {
        listen  8080;
        server_name example.com;             
        root /tmp/test/example;
        location / {
            index index.html;
            try_files $uri /test.html;
        }

    }
}

When I access example.com:8080, it accesses the /tmp/test/example/test.html, not the index.html.

like image 642
zhenguoli Avatar asked Mar 23 '16 10:03

zhenguoli


People also ask

How does nginx try_files work?

NOTE: Nginx try_files directive recursively searches for files and directories specified from left to right until it finds ones. Specifying this directive in the location / can cause performance issues, especially on sites with massive traffic. Therefore, you should explicitly specify the location block for try_files.

What is $URI in nginx conf?

According to nginx documentation, $uri and $document_uri contain the normalized URI whereas the normalization includes URL decoding the URI. Every file requested under /static/ folder will be redirect to another server, in this case example.com.

What is alias directive in nginx?

NGINX Alias Directive Alias directive allows you to remap URLs to a different directory other than root location. It is useful for serving static files from a different directory. For example, if Alias is /var/www/html/css for location /static/, then when a user requests /static/style.

What is index in nginx?

The index directive defines the index file's name (the default value is index.html ). To continue with the example, if the request URI is /images/some/path/ , NGINX delivers the file /www/data/images/some/path/index.html if it exists. If it does not, NGINX returns HTTP code 404 (Not Found) by default.


1 Answers

The try_files directive is documented here.

It specifically documents two file elements: $uri and $uri/. The first tests for the presence of normal files and the second for the presence of directories.

The index directive is invoked as a consequence of processing a URI which points to a directory which contains a file matching one of the directives parameters.

In the case of try_files $uri /test.html;, the existence of a directory is not tested, and therefore the default action is taken.

In the case of try_files $uri $uri/ /test.html;, the existence of a directory is tested, and therefore the index action is taken.

like image 70
Richard Smith Avatar answered Nov 02 '22 21:11

Richard Smith