Using different redirects across different contexts/environments

Hi all,

I currently have 3 different branches in Github (dev/test/prod) and 3 API servers (dev/test/prod) on non-Netlify domains, and I am currently using the Netlify _redirects file to handle redirection of API calls to these domains. For example, dev would have a redirects file like:

/api/*         http://dev.my-api-instance.amazonaws.com/:splat          200

And Test would have a file like

/api/*         http://test.my-api-instance.amazonaws.com/:splat          200

My problem is when I create pull requests from one environment to another (e.g. Dev to Test) - these _redirect files get overwritten in the pull request (e.g. /api/* for test starts pointing to dev server) and I have to manually rewrite these files after accepting the pull request.

I would avoid committing the _redirects file in Git, but then Netlify wouldn’t be able to read it. Alternatively, I would use different contexts in netlify.toml to have my redirect rules vary for each environment, but redirects seem to be a special case and can’t be set per-context in this file.

Is there any way I can avoid manually rewriting the _redirects file for each branch merge? I only need to set these very infrequently, but I merge branches often.

I was able to work around this by creating an additional branch for the _redirects file change. For example, if I was promoting work from Dev to Test:

  1. Create a new branch from Dev (e.g. ‘devtotest’)
  2. Update the _redirects file with the Test API server location in devtotest branch
  3. Pull request from devtotest to Test branch

Not great, and somewhat error prone, but at least i’m not changing live pages as I go. Still interested in a better approach.

Hi @dvasdekis,

We have an open feature request to support putting redirects in deploy context, I’ve added your voice to this request so we’ll let you know once it’s been added.

What most people do in this situation is to write a script, could be in any language or just do it in bash. This script checks the BRANCH or CONTEXT and depending on what is there, it renames a file. This way you prepare multiple _redirects files with different names, and rename the one you want to be active to _redirects. You can also dynamically generate a _redirects file inside of a script during your build process if you prefer doing it that way.

1 Like

Thanks Gerald. Any way I can keep track of this feature request, so I know when I can switch?

@dvasdekis, the feature request isn’t publicly accessible. This community topic and the feature request are “cross-linked” though.

We will definitely follow-up here in community if/when the feature is added to let you (and anyone else searching here) know about it.