1

I would like to serve an index file from a root folder and one from a subfolder from root.

My nginx server conf looks as follows:

server {

    listen       80;
    server_name  localhost;
    root /data/;
    index  index.html index.htm index.txt;

    location / {
    }

    location /a {
        alias   /data/a/;
    }

}

and my directory structure looks as follows:

/data/:
a  index.txt

/data/a:
index.txt

If I then do curl localhost, I get the contents of the file /data/index.txt. But curl /localhost/a gives me a 301. curl localhost/a/index.txt works.

Why can't I access my index.txt with curl /localhost/a ?

I tried using a root instead of alias in the location /a block and also tried to specify the index.txt for location /a, but no success.

I see similar posts, e.g. Nginx location configuration (subfolders) but couldn't yet find the answer.

user1981275
  • 13,002
  • 8
  • 72
  • 101
  • I see that when I first call `curl localhost/a/index.txt` and then right afterwards call `curl localhost/a`, it works, but then nginx seems to forget this again and I get a 301. – user1981275 Feb 26 '20 at 12:36
  • I am not sure if i got you right but why are you trying to create an alias to the same uri ex: if you brows `/a` it will automatically brows `a` subfolder and serve index.txt no need for an alias in this case ! – lotfio Feb 26 '20 at 14:30

1 Answers1

0

The index directive works with URIs that end with a /:

So the URI / gives you the contents of /index.txt and /a/ gives you the contents of `/a/index.txt.

If you provide Nginx with a URI of a directory (but without a trailing /), the default behaviour is to redirect to the same URI, but with a trailing /.

This is just how the index directive works. See this document for details.


If you want something other than default behaviour you will have to do it manually using try_files. See this document for details.

For example, to return the contents of an index.txt file by providing the URI of the directory without a trailing /, use:

root /data;

location / {
    try_files $uri $uri/index.txt =404;
}

Note that the location /a { ... } block is not necessary in either this example, or the example in your question.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81