Redirects: match any number of sub-folders

I was able to make basic redirects work, but I am trying to do this:

  • redirect /**/old-slug to /new-slug

And by ** I mean I want to match and remove any variations of folders and sub-folders, no matter how many levels.

I need to do 301 redirects for 3000 different old-slugs to 3000 different new slugs.

Can this be done?

Thank you!

Hey @fplanque! :wave:t2:
Welcome to the Community :slight_smile:

Great question. Haven’t heard or thought about this one yet.

Did some testing locally via Netlify Dev (which runs the same redirect engine as Netlify Prod I believe) and did find that splats support after-the-splat path filters… which is news to me and also so cool.

Redirects aren’t quite UNIX-style directory pathing, so you don’t need the double star, but in testing this rule (in _redirects file format, not toml format):

/*/foo /bar

I got the following results

/something/somewhere/foo -> 302 -> /bar

and further, the :splat directive actually does work to re-add those path values if you need to (cool!)… so with the redirect changed to:

/*/foo /bar/:splat

I got the following results

/something/somewhere/foo -> 302 -> /bar/something/somewhere

Tl;dr: yes; single star though

Hope that helps! Thanks for the great question!

–
Jon

PS - Always feel free to reference the redirects docs for more info :+1:t2:

1 Like

Woot!? It works already!?

The man page mislead me into thinking that splats can only be at the end of the URI string!

Thank you so much for making the test that poor me didn’t even try to make :stuck_out_tongue:

Awesome news !

Well lucky for you I have a ton of local Netlify dev sites and your question made me curious! :rofl:

For documenting things’ sake - I missed a potential use case - using the :splat in the to field but not at the end:

Rule: /*/foo /:splat/bar

Test:
/something/somewhere/foo -> 302 -> /something/somewhere/bar :white_check_mark: aww yee :sunglasses:

Enjoy!

–
Jon

P.S.S - I haven’t looked at the code (but it is open source, so we could) but I’m pretty sure the redirect engine just runs JS Regex’s so bare in mind, you can get pretty wild :wink:

1 Like

I have this working fine now on a simple test site (static html). Great! Thanks! :slight_smile:

On another site (build with Jekyll), absolutely no redirect works, even the most trivial ones. Are there situations where the _redirects file might be ignored? What am I missing?

The _redirect file must be present in the publish directory. Depending on where you put it in your Jekyll project hierarchy, there’s a good chance it’s not getting pushed over to the publish directory.

Jekyll also ignores files that start with an underscore by default.

Add

include: [
  '_redirects'
]

to your Jekyll config :ok_hand:t2: