ptr
ptr

Reputation: 3384

nGinx, multiple locations serving different SPAs

I have a very simple config that I want to use to serve multiple single page apps

server {
    root /var/www/;
    index index.html;

    location ~ ^/spa1/(.*?)$ {
        root /var/www/spa1/;
    }

    location ~ ^/spa2/(.*?)$ {
        root /var/www/spa2/;
    }

    error_page 404 /404.html;
}

The directory structure of /var/www/ is as below:

www/
|- 404.html        (Generic 404)
|- index.html      (A plain html page with links to the apps)
|- spa1/   
   |- index.html   (the index page for single page app 1)
   |- spa1.js
   |- spa1.css
   |- static/      (folder containing spa1 static files)
|- spa2/
   |- index.html   (the index page for single page app 2)
   |- spa2.js
   |- spa2.css
   |- static/      (folder containing spa1 static files)

My understanding was that vising myserver.com/ would return the index.html page in /var/www, whereas visiting myserver.com/spa1/ or myserver.com/spa2/ would return the respective index.html pages for each single page app. However this doesn't seem to be the case- instead if I visit /spa1 or /spa2 I get served the root index.html page only, as if it's ignoring the root directive for each app

As an addendum, is there a more correct way to serve multiple single page apps than the way I'm attempting to do it?

Upvotes: 1

Views: 541

Answers (1)

Richard Smith
Richard Smith

Reputation: 49692

I do not understand why the URI /spa1/ would return the file /var/www/index.html, with your current configuration. However...

The value of the root statement should be /var/www for all three cases. The path to the file is calculated by concatenating the value of the root statement with the URI.

So your directory structure and URI plan should work with the even simpler configuration of:

server {
    root /var/www;
    index index.html;

    error_page 404 /404.html;
}

See this document for details.

Upvotes: 1

Related Questions