I am trying to understand how nginx's try_files directive works. nginx is running on my server and serving up the default page located at /usr/share/nginx/html/index.html
.
However, I have a simple html page located in the filesystem at /var/www/test/index.html
. The following config file is not causing that file to get served. I'd like to understand why not, and what change I need to make so that it will be served.
Here is the relevant portion of defualt.conf:
server {
listen 80;
server_name localhost;
root /var/www;
try_files /test/index.html /;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
a very common try_files line which can be applied on your condition is
you probably understand the first part,
location /
matches all locations, unless it's matched by a more specific location, likelocation /test
for exampleThe second part ( the
try_files
) means when you receive a URI that's matched by this block try$uri
first, for examplehttp://example.com/images/image.jpg
nginx will try to check if there's a file inside/images
calledimage.jpg
if found it will serve it first.Second condition is
$uri/
which means if you didn't find the first condition$uri
try the URI as a directory, for examplehttp://example.com/images/
, ngixn will first check if a file calledimages
exists then it wont find it, then goes to second check$uri/
and see if there's a directory calledimages
exists then it will try serving it.Side note: if you don't have
autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.Third condition
/test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the fileindex.html
inside the foldertest
and serve it if it exists.If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
You can call it with
try_files
like thisTIP: If you only have 1 condition you want to serve, like for example inside folder
images
you only want to either serve the image or go to 404 error, you can write a line like thiswhich means either serve the file or serve a 404 error, you can't use only
$uri
by it self without=404
because you need to have a fallback option.You can also choose which ever error code you want, like for example:
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..