2

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?

PhilHarmonie
  • 143
  • 2
  • 7

1 Answers1

0

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.

Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63
  • But why am I not seeing 404 for `/var/www/test/test/index.html`? – PhilHarmonie Jan 16 '22 at 09:54
  • 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. – Tero Kilkanen Jan 16 '22 at 09:59