reactjshttp-redirectproxynetlify

Netlify _redirects file not working as expected


I have my _redirects file in the public folder of my react app and I added a redirect rule /* /index.html 200, which works perfectly.

Then I added another rule to proxy my app to my api server /api/* https://api.com/ 200! it doesn't work.

the whole file looks like this

/*   /index.html  200
/api/* https://api.com/ 200!

As I stated, the global redirect /* overrules the /api/* and I couldn't get it to work.

NOTE: I have tried rearranging them like this

/api/* https://api.com/ 200!
/*   /index.html  200

and in this case, the app get's stuck on 'page not found'


Solution

  • NOTE: I have tried rearranging them like this

    /api/* https://api.com/ 200!
    /*   /index.html  200
    

    and in this case, the app get's stuck on 'page not found'

    You are stuck at 404 beacuse https://api.com/ handles home route as a 404 from your backend(when your url in Browser address bar is like: /api/blah/blah).

    With this rule /api/* https://api.com/ 200!, the asterisk (*) on /api is used to indicate anything that follows /api/ to be matched to https://api.com/(home route).

    This is a problem because what you want is https://api.com/ matched to anything that followed /api/ as well, for example;
    /api/blog/2010 should be matched to https://api.com/blog/2010.
    But the current behaviour is /api/blog/2010 is matched to https://api.com/

    Solution

    This is how your _redirect file should look like:

    /api/* https://api.com/:splat 200!
    /* /index.html  200
    

    You need to specify splat.
    Using an asterisk on the from URL(/api/*), you also need to indicate a splat on the to URL(https://api.com/:splat) that will map to anything that follows /api/*. So a URL like /api/blog/2010 will be written to https://api.com/blog/2010

    Bonus

    The Netlify redirects engine will process the first matching rule it finds, reading from top to bottom.

    So an ordering like:

    /* /index.html  200
    /api/* https://api.com/:splat 200!
    

    Means that the first redirect rule(/* /index.html 200) will process since it always matches. The second one(/api/* https://api.com/:splat 200!) won’t be hit it, even when browser address bar is like /api/blah/blah. Even if you have ! on a rule, the order of redirects is still followed.

    More specific rules should be defined at the top. As shown:

    /api/* https://api.com/:splat 200!
    /* /index.html  200