Nginx configuration for server-side rendering of static assets, a node request handler, and index.html fallback

nginx

I want to serve an app that's built with webpack and therefore can always be served statically, but I want to put a node server (with JSDOM) that'll pre-render the HTML for each request. The node server should only be hit for requests that cannot be served statically, and if the server is taken out these requests should then be redirected to serve the static index.html

So, nginx should do the following in this order:

  1. Serve all asset files (app.js,css,etc) except index.html statically
  2. Proxy all other requests (/users,/products/,etc) to node app
  3. If above proxy fails, serve index.js for all those requests

Best Answer

I'm currently using this which seems to be working

server {
  root /my-app;

  location / {
    try_files $uri @node;
  }

  location @node {
    proxy_pass http://localhost:8000;
    error_page 502 = @static;
  }

  location @static {
    try_files $uri /index.html $uri;
  }
}
Related Topic