skip to Main Content

I use react-router-dom in my react application like this:

import {BrowserRouter, Route, Routes} from "react-router-dom";
// other code...
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
    <BrowserRouter>
        <Routes>
            <Route path="equipe" element={<Equipe/>}/>
            <Route path="equipe/:id" element={<Equipe/>}/>
            {/*other route...*/}
        </Routes>
    </BrowserRouter>
);

I specify that by launching my application in development mode with react-scripts start I have no worries.

I build my project by running react-scripts build, which works.
I’m using the following nginx configuration:

server {
   server_name server_name_url;
   location / {
            root /path/to/folder/build;
            try_files $uri $uri/ /index.html;
   }
   listen 443 ssl; # managed by Certbot
   # other elements managed by Certbot
}

When I access server_name_url/equipe it works fine.

When I access server_name_url/equipe/:id (server_name_url/equipe/12345 for example) it returns me the index.html file instead of the main.396fb688.js file.

I understand why (related to try_files which can’t find $uri and $uri/).
enter image description here

How can I modify the nginx configuration in order to access my /equipe/:id route please ?

2

Answers


  1. The issue you’re encountering is that the requests to the index.html file are functioning properly, but you need to configure nginx to also redirect other requests to the index.html file too.

    To resolve this, you need to update your nginx configuration to include a fallback route that directs all requests to the index.html file. This ensures that your application’s routing system can handle the requests appropriately.

    location / {
      try_files $uri /index.html;
    }
    
    Login or Signup to reply.
  2. I might have found a solution for your issue here. I had the same problem, it was because the environment variable PUBLIC_URL was not defined to /.
    So I had to add to my .env file:

    PUBLIC_URL=/
    

    Try that one

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search