nginx config with spa and subdirectory root
Asked Answered
B

1

15

I always seem to have problems with nginx configurations. My SPA is located at /mnt/q/app (pushstate is enabled) and the frontend root is located at client/public. Everything should be mapped to index.html, where the app picks up the route and decides what to do.

Full path to the index is /mnt/q/app/client/public/index.html.

I think I ran out of options by now. No matter what I do, I just get a 404 back from nginx, I think the configuration is simple enought and have no clue what's wrong.

server {
    listen 80;
    server_name app.dev;

    root /mnt/q/app;

    location / {
      root /client/public;
      try_files $uri @rewrites =404;
    }

    location @rewrites {
       rewrite ^(.+)$ /index.html last;
    }
}

Any help is appreciated.

Barragan answered 21/5, 2017 at 14:40 Comment(0)
T
24

If nginx views the file system from the root, then the root should be set to /mnt/q/app/client/public, and not either of the two values you are using.

The last element of the try_files directive can be a default action (e.g. /index.html), a named location or a response code. You have a named location in the penultimate element - which will be ignored.

Your named location should work, but is unnecessary, as try_files is capable of implementing it more simply. See this document for more.

For example:

root /mnt/q/app;

location / {
    root /mnt/q/app/client/public;
    try_files $uri $uri/ /index.html;
}

location /api {
}

location /auth {
}

The $uri/ element will add a trailing / to directories, so that the index directive can work - you do not have to add it if you do not need it.

Tropho answered 21/5, 2017 at 15:0 Comment(2)
Thank you for the response. I'd however like to add multiple locations in the future. For example, I'll add api and auth components, which I'd like to be at /api and /auth, while the path should be at /mnt/q/app/api/ and /mnt/q/app/auth respectively. I'm not sure if I can do that with this approach. I used this gist as a "template": gist.github.com/aotimme/5006831Barragan
The local path is formed by concatenating the root value with the URI, so the /api and /auth blocks would use the same value for root (which can be inherited from the outer block). I presumed that /index.html is the URI for the file mentioned in your question, which needs a different value for root. See updates.Tropho

© 2022 - 2024 — McMap. All rights reserved.