How to set different context path for React app in NGINX

Viewed 1885

I have deployed (using Kubernetes/helm charts) React app to http://localhost:30111/ using embedded NGINX. This single page application requires some NGINX rewrite rules for deep linking of static sources. There are following NGINX rules:

 server {
  server_name _;

  gzip on;
  gzip_static  on;

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

Everything works fine and application is listening on http://localhost:30111/ as expected.

What I need to do: I need to use new context path for this application e.g. http://localhost:30111/myapp instead of root context path http://localhost:30111/.

How should I write proxy_pass/rewrite rules in NGINX to work on new context path?

1 Answers

Even though its late, i will provide my answer which may help someone later.

  1. As a first step move all the files in the build folder to a sub directory which is same name of context path.

build/myapp/...All static files will be placed here.

  1. Add your context path in package.json file

"homepage": "/myapp" -- this will help set process.env.PUBLIC_URL to /myapp

  1. Add Basename in the BrowserRouter

          <BrowserRouter basename={process.env.PUBLIC_URL}>
              <Suspense fallback={<Loader />}>
              // ... app routes...
              </Suspense>
            </BrowserRouter>

  1. Change in your nginx configuration to use files from your sub directory

     location / {
      return 301 /myapp;
    }
    location ~ ^/myapp {     
      
      try_files $uri /myapp/index.html;

  1. You are done. Deploy your application and see Ui redirects directly to your context path and serving the files.
Related