0

I have a SPA application, written in ReactJS. The application has an index view (/myapp) which shows a list cards. Pressing on a card redirects to a new page via routes (/myapp/item, /myapp/itemXX). The application works fine when the user access from the index. However, refreshing the browser in /item ends up in a 404 Not Found error.

The server is NGINX and the configuration looks like:

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

In the log file I see:

{
  "log": "2019/12/26 08:32:36 [error] 178#178: *3146 open() \"/etc/nginx/html/index.html\" failed (2: No such file or directory), client: 46.222.205.233, server: app.mydomain.com, request: \"GET /myapp/item/8?param=888 HTTP/2.0\", host: \"app.mydomain.com\"\n",
  "stream": "stderr",
  "time": "2019-12-26T08:32:36.253097755Z"
}

I have already tried several location rules without success (location ^~ /myapp, creating specific rule for internal routes location /myapp/item).

Any help? Thanks!

rb612
  • 5,280
  • 3
  • 30
  • 68
Andrés
  • 719
  • 1
  • 4
  • 21
  • Hi this thread might be useful https://stackoverflow.com/questions/43555282/react-js-application-showing-404-not-found-in-nginx-server – t3__rry Dec 26 '19 at 09:06
  • Thanks for your time. I have just tried but It does not work in my case. The only different I see is that my app is not in the root (/'') but in '/myapp'. – Andrés Dec 26 '19 at 09:10
  • 1
    Have you tried to setup your root like explained in this answer? https://stackoverflow.com/questions/45598779/react-router-browserrouter-leads-to-404-not-found-nginx-error-when-going-to#answer-45656036 – t3__rry Dec 26 '19 at 09:17
  • It looks more-so based on the logs that `/etc/nginx/html/index.html` doesn't exist—are you sure there's a file at that path and it's what you expect (the root file for React)? – rb612 Dec 26 '19 at 09:23
  • @t3__rry I'm not using heroku, just NGINX in my own server, thanks! – Andrés Dec 26 '19 at 11:48
  • @rb612 that file exists, but it should not try to load it. It should send the file in the corresponding folder (/etc/nginx/html/myapp/index.html). Something is wrong with the routes. – Andrés Dec 26 '19 at 11:53
  • 2
    The `try_files` directive expects a URI as the last parameter, so you should use: `try_files $uri $uri/ /myapp/index.html;` – Richard Smith Dec 26 '19 at 14:09

1 Answers1

0

I found this question, which summarizes how routing works in both, server and client side:

React-router urls don't work when refreshing or writing manually

The solution that works for me is:

location /myapp {
  if (!-e $request_filename){
    rewrite ^(.*)$ /myapp/index.html break;
  }
}
Andrés
  • 719
  • 1
  • 4
  • 21