0

I was trying to use nignx try_files in the "server" block. I arrived at this question: Nginx try_files doesn't work inside server block

My use case is different, because there is only cache header settings in the location block:

 server { listen 80; root /app; index index.html; try_files $uri $uri/ /index.html; location /assets/ { add_header "Cache-Control" "public"; expires 1d; } location / { add_header "Cache-Control" "no-cache"; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } 

I already read How nginx processes a request, but i'm still confused why it doesn't work.

In the comments on the above question someone mentioned that try_files has been moved to ngx_http_try_files_module.

On the nginx documentation page, i can't find this module, and try_files is still documented in the core module: https://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

According to this try_files can be used in the server block, so i can't understand why my config doesn't work.

Can some explain/point me to the right direction?

2 Answers 2

1

try_files will be executed in the location block chosen to process the request.

The try_files in the server block will only be executed if no matching location is found.

Since you have location / present in your configuration, there will always be a matching location, so the try_files in server will never get executed.

Copy try_files into each location block that needs it.

0

I finally found a great article that explains it:

The try_files directive is mostly like every other action directive mentioned above, the difference is that if placed in server context nginx actually creates a pseudo-location that is the least specific location possible. That means if a request matches a defined location the try_files directive will not be executed. This means that if you have location / defined then you have a location that matches every possible request and as such try_files will never actually execution. Therefore always place try_files in location context instead of server context if at all possible.

It also contains some info about how inheritance works between the nginx context blocks (global, http, server, location, etc.), working differently for different kinds of directives.

see: https://blog.martinfjordvald.com/understanding-the-nginx-configuration-inheritance-model/

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.