Score:2

403 in nginx when accessing a directory

cn flag

I made a very simple server to test how a URL with folder behaves in nginx. Nginx is running in docker (nginx:latest image). Nginx runs user nginx (default set in /etc/nginx/nginx.conf).

server {
        server_name example.com;

        location /test/ {
                root /var/www/test;
                index index.html;
        }
}

and this structure:

/var/www
└── test
    └── index.html

cat /var/www/test/index.html
Test

ls -l /var/ | grep www
drwxr-xr-x 3 root  root 4096 Jan 15 23:33 www

ls -l /var/www/test/
-rw-r--r-- 1 root root 7 Jan 15 21:08 index.html

Now I have this issue:

curl http://example.com/test/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.21.5</center>
</body>
</html>
curl http://example.com/test
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.21.5</center>
</body>
</html>

I expect to see "Test" when I access http://example.com/test or http://example.com/test/. What am I doing wrong?

Score:0
us flag

Two separate things are happening.

nginx appends the request URI at the end of path of root directive when serving the request. In your case, the URL is, http://example.com/test, the normalized URI is /test and your root is /var/www/test.

This makes nginx look for index.html in /var/www/test/test/index.html.

To make nginx server /var/www/test/index.html, you need to either use:

root /var/www;

or

alias /var/www/test;

Using root is the preferred way.

For the http://example.com/test part, nginx sends a 301 redirect to http://example.com/test/ when there is a directory test on the server. Your question does not show what is the root directive in the upper level, so I don't know in which path the existence of test is checked.

PhilHarmonie avatar
cn flag
But why am I not seeing 404 for `/var/www/test/test/index.html`?
us flag
Actually nginx returns 403 for `http://example.com/test/` and 404 for `http://example.com/test/index.html` request with your current configuration. Why exactly nginx works like this, I don't know.
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.