0
votes

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!

1
Hi this thread might be useful stackoverflow.com/questions/43555282/…t3__rry
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
Have you tried to setup your root like explained in this answer? stackoverflow.com/questions/45598779/…t3__rry
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
The try_files directive expects a URI as the last parameter, so you should use: try_files $uri $uri/ /myapp/index.html;Richard Smith

1 Answers

-1
votes

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;
  }
}