Nginx and Create React App (with React Router) full routes not working Nginx and Create React App (with React Router) full routes not working nginx nginx

Nginx and Create React App (with React Router) full routes not working


The way I currently have this working in a project is by adding a homepage field in my package.json file in the React app.

{  "name": "react-app-name",  ...dependencies and such  "development": [      "last 1 chrome version",      "last 1 firefox version",      "last 1 safari version"    ]  },  "homepage": "https://example.com/app",  "proxy": "https://example.com/api"}

You need this in addition to the basename property you already have in your Router component. This should allow you to render those pages through the React Router. I assume the pathing in your NGINX file is correct if you can see the example.com/app.


A web server, 'serves' files. When you visit example.com/app, the webserver is just showing whatever is in /usr/share/nginx/html/app/index.html, likewise if you visit example.com/app/login, it will try to display what is in /usr/share/nginx/html/app/login/index.html

Without seeing or knowing how you built the react app, it's a little hard to know what the problem is. React, when you build will just create the single index.html along with a bunch of javascript inside the build directory.

This is why you can see it on your react homepage (www.example.com/app). But when you navigate to example.com/app/login you can't. Because there is an index.html for /app, but not for /app/login. Nginx is expecting an .html file under the /app/login directory.

Quick Solution:Most people will use React Router to create a multipage react app. This allows you to have routes within the react app.

Even though you only have the single index.html, you can create different 'pages' using react-router and it's all handled by the built javascript and you don't have to worry about creating a bunch of routes in Nginx. Just route to the react main app and react-router will handle the rest!


As @codebytesfl mentioned you need to make nginx to return you react app index.html for all the paths that are under /app/ (because your react app handles routing at the client side).

I think that the root cause is the usage of alias directive.

try_files is appending $uri onto the path already set with alias.For more details read this

Try to change the alias to root

    location /app/ {        root /usr/share/nginx/html/app/;        try_files $uri $uri/ /index.html;    }