0

When deploying a react application behind nginx, it's a common problem to encounter a 404 error when going to your react routes directly instead of navigating to them from your root index.html.

The fix for this is usually to use this in nginx.conf

location / {
 try_files $uri /index.html;
}

Ref: react.js application showing 404 not found in nginx server

This is a very common fix, but the issue with this solution, is it cancels nginx default handling of non-existing routes to return 404

Is there a way to keep handling react routes, but still return 404 for non-existing routes?

I have tried this but it doesn't work, it returns 404 on /route1 and 500 on non-existing routes

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;

        set $fallback_file /null;

        if ($uri ~ /$) {
            set $fallback_file /index.html;
        }

        if ($uri ~ /route1$) {
            set $fallback_file /index.html;
        }

        try_files $uri /index.html;
    }
Yousef Hamza
  • 347
  • 1
  • 3
  • 13

1 Answers1

0

This is the solution I found so far, it's manual; you have to add each route manually in nginx.conf as well. So I will leave it here until someone finds a better solution

    location = /route1 {
        try_files $uri /index.html;
    }
Yousef Hamza
  • 347
  • 1
  • 3
  • 13