Serving a ReactJS app using nginx via a directory

I've got a ReactJS app which works fine if served from the root of a subdirectory using the following code:

server {

   listen  80;

   server_name sub.domain.net;

   root /var/www/vhosts/sub.domain.net/httpdocs;

   location / {
      try_files $uri $uri/ /index.html;
   }
}

However I'd like to serve this from the main domain.net instead, and getting errors in all previous attempts. Here's what I have and it definitely does not work, the same ReactJS files are within a directory off of the root:

server {
  listen  80;
  server_name domain.net;

  root /var/www/vhosts/domain.net/httpdocs;

  location / {
      try_files $uri $uri/ /index.html;
  }

  location /reactapp {
      try_files $uri $uri/ /index.html;
  }
}

When using it in this manner, I'm getting an Uncaught SyntaxError: Unexpected token < and it's attempting to serve the stylesheet and likely the .js from the root rather than the directory.

The app is built using webpack, and does work perfectly fine off of a subdirectory. Thanks everyone!


Solution 1:

I was struggling with the same problem. Finally I was able to solve it using official documentation and a combination of answers:

Assumptions:

  • Your React App is based on create-react-app package (you are using react-router-dom).
  • You are using Nginx and the root path is being used by another service (or even another React/Gatsby App which is my case).
  • You want to deploy the React App on a subdirectory and be able to serve all statics of your React App from that subdirectory.

React App Changes:

Based on official documentation.

  1. Update your BrowserRouter by adding a basename. Example: <BrowserRouter history={history} basename="/webapp">.
  2. Specify a homepage on your package.json. Example: "homepage": "/webapp".
  3. If you are referencing a static file by its relative path, you should add the subdirectory to that reference. Example: src="/static/logo/logo.png" becomes src="/webapp/static/logo/logo.png".

Nginx Changes:

location ^~ /webapp {
   alias /var/www/myapp/build;
   try_files $uri $uri/ /webapp/index.html;
}

Solution 2:

For custom path:

Before configuring your nginx server, you need to specify the destination path in app's package.json as "homepage": "/reactapp"

  location /reactapp {
      try_files $uri $uri/ /index.html;
  }

For root path:

If you want to host in root of the domain, make sure you've given nothing for key "homepage": "", better remove it from package.json and configure nginx as below

  location / {
      try_files $uri $uri/ /index.html;
  }

Note: You can use either path but can't configure two different path at same time. Your app will works for what you configured in package.json

Source: Apache Nginx Rewrite Configuration - React.js | Andro Babu Blog