How to map a location to a path in NGINX

I have an nginx setup where I need to map specific url paths to server paths. For example I need example.test/myapp/ to go to the following directory in the server: /apps/myapp/web

I tried adding the following location block:

location /myapp/
{
    root /apps/myapp/web;
}

but if I go to example.test/myapp/ or example.test/myapp I get a 404.

As far as I can tell according to the docs this location should capture anything with a path that starts with /myapp/ and it's the only location block in the server so there's no chance of conflict. Also I've tried changing the location to point to the root (i.e. location /) and it works fine so it's not a problem of the wrong server path or missing files. What am I missing?


nginx resolves file paths by using following strategy:

  1. Use path from root directive
  2. Add URI from request after the directive.

Now, in your case:

  1. root is /apps/myapp/web.
  2. URI from example.test/myapp/ is /myapp/.

Therefore nginx looks up files in /apps/myapp/web/myapp/ directory for that request.

If you want that /myapp/ URI will get files from /apps/myapp/web/ directory, you need to use the alias directive:

location /myapp/ {
    alias /apps/myapp/web/;
}