Score:2

How to map a location to a path in NGINX

vn flag

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?

Score:5
us flag

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/;
}
vn flag
Thanks! Where I got turned around is with the example in the docs where they say: `location ~ \.(mp3|mp4) { root /www/media; }` will return all video files at `www/media`. So prefix locations append the URI but regular expression locations don't?
us flag
Yes, regular expressions don't append the URI, because it is difficult to determine which part of the regular expression match should be appended.
co flag
@Mattia No, regex locations follow the same rule as normal location blocks, URL `/myapp/test.mp4`, root `/www/media` becomes `/www/media/myapp/test.mp4`
vn flag
using the alias results in returning 403s for everything. (I know it's not actually a permissions issue since I was able to server the files with other location blocks). It was fixed by adding a trailing slash to the alias: `alias /apps/myapp/web/`. Not sure why that is...
us flag
Interesting. I don't use `alias` myself, so I didn't know it required slash at the end. Good that you figured it out, I updated my answer.
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.