Search code examples
nginxsingle-page-applicationaurelia

nginx config with spa and subdirectory root


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.


Solution

  • 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.