1
votes

I have a react router with routes which looks like this.

const Main = () => {
  return (
    <main>
      <Switch>
        <Route exact path="/" component={FileUploader} />
        <Route path="/user-jobs" component={UserJobs} />
        <Route component={NoMatch} />
      </Switch>
    </main>
  );
};

Lets assume the domain where the app to be hosted to be app.in. I want my app's homepage to be available at http://app.in/app/v2/uploader.

Here is my nginx config in /etc/nginx/sites-enabled/app.conf

server {
    listen 80;
    underscores_in_headers on;
    server_name app.in;

    root /var/web;
    index index.html index.htm;

    location /app/v2/uploader {
          try_files $uri /app/v2/uploader/index.html;
     }

}

My apps build folder is available at /var/web/app/v2/uploader. When I deploy the app, the paths (http://app.in/app/v2/uploader, http://app.in/app/v2/uploader/user-jobs) hit the Route with NoMatch component but the not the intended components. This problem arises only when I use BrowserRouter, HashRouter works as expected.

Since I am relatively new to nginx can anyone please guide me as to how to achieve the required result?

1

1 Answers

1
votes

I figured out the answer myself. My nginx configuration was all fine, but the problem was with the way I had configured my router. The expected location is /app/v2/uploader but I was looking for / in my path. So dynamically prefixed the base path something like this.

const urlParts = window.location.pathname.split("/");
const base = urlParts.slice(0, urlParts.length - 1).join("/");

After having done this prefixed the base to the path props and it all works fine.

 <Route path={`${base}/user-jobs`} component={UserJobs} />