Nginx: Root inside location block

I think the example given in documentation is not great. In it, the / location will catch any non-matching routes, so having no route outside location blocks will probably not make any difference. from digitalocean, I found this explanation:

root /var/www/main;

location / {
    error_page 404 /another/whoops.html;
}

location /another {
    root /var/www;
}

Every request (other than those starting with /another ) will be handled by the first block, which will serve files out of /var/www/main . However, if a file is not found (a 404 status), an internal redirect to /another/whoops.html will occur, leading to a new location search that will eventually land on the second block. This file will be served out of /var/www/another/whoops.html .

Looking further in the nginx documentation:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

The “ / ” request will match configuration A, the “ /index.html ” request will match configuration B, the “ /documents/document.html ” request will match configuration C, the “ /images/1.gif ” request will match configuration D, and the “ /documents/1.jpg ” request will match configuration E.

If a location block for a request doesn’t exist and there is no root outside , there is no default location to send the request. Even if it results in an error, it should at least point to a valid folder where the request can be processed and the error handled.

At least that’s what I think. I could be wrong.

1 Like