Artem Z
Artem Z

Reputation: 565

Serve both static website & SPA (node.js) with NGINX

I need a way to serve both static html website and SPA using NGINX.

So, if there's an appropriate static html route it should be served with NGINX, any other route should be served by node.js webserver.

e.g.

https://website.com/about -> served by NGINX because there's about.html https://website.com/register -> served by node.js because there's no appropriate static page for this route (there's no register.html).

I've created the following configuration, but it doesn't seems to work properly.

upstream backend {
    server localhost:8080;
}

server {
    listen 80;
    server_name website.com www.website.com;

    root /var/www/website.com;

    location = / {
        try_files /index.html =404;
    }

    location = /index {
        return 404;
    }

    location / {
        try_files $uri/index.html =404 @backend;
    }

    location @backend {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

Upvotes: 1

Views: 898

Answers (2)

Shawn C.
Shawn C.

Reputation: 6841

You could try something like

location / {
    try_files $uri $uri.html $uri/ @backend;
}

Breaking it down for you. The try_files directive

Checks the existence of files in the specified order and uses the first found file for request processing;

So

$uri - look for the exact file as defined in the path. Useful for static files like css, images, js, etc..

$uri.html look for the exact file with a .html extension. This would get your about.html

$uri/ - looks for it to be a directory then uses the index directive to look for index or index.html

@backend - send to the proxied application would be responsible for returning 404

Upvotes: 1

Richard Smith
Richard Smith

Reputation: 49752

Your configuration could probably be simplified to this:

root /var/www/example.com;
index index.html;

location / {
    try_files $uri $uri/ @backend;
}

location @backend {
    ...
}

Upvotes: 2

Related Questions