Search code examples
reactjsnginxreact-router-domnginx-configreact-dom

react-router-dom & nginx -> path /equipe/:id return index.html


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 ?


Solution

  • 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