Have redirects that don't match to a file result in 404

Is it possible to have a rewrite wildcard that matches but doesn’t match a corresponding file in the build so it results in a custom 404? Let me explain:

I want to support a bunch of dynamic paths under /resource. It could be /resource/123 and it could also be /resource/456. I want all of those to look for a specific index.json file under their paths. If one of those doesn’t exist, serve up a 404 status code with an errors file. So I have a redirects file like this:

/resource/* /resource/:splat/index.json 200
/resource/* /error.json 404

Now, let’s say my final build results in a set of files like this:


If a request is made for a file that exists in my build, like /resource/123, that matches my rewrite wildcard /resource/* and /resource/123/index.json gets served up. Great!

If a request is made for a file that does not exist in my build, like /resource/000, that still matches my /resource/* wildcard, so Netlify follows that rule and tries to serve up /resource/000/index.json. That file, however, does not exist in my build, so the generic 404.html page gets served. What I want, instead, is to have the /error.json file get served with a 404.

Is there a way to express rewrites in the way I’m describing? i.e. if a wildcard matches, look to serve that file unless it doesn’t exist, in which case keep matching against other rewrite/redirect rules and if no rules match then serve the 404.html?

Is my question clear?

The only way I can think around this is to build up a huge list of paths during my build (i.e. [/resource/123, /resource/456, ...], write an explicit rule for each of those in my redirects file instead of using a wildcard (i.e. /resource/123 /resource/123/index.json 200) then have a generic wildcard that matches everything under /resource/* be a 404. In the example above of /resource/000 I believe that would result in Netlify properly serving a 404 because every known path has an explicit rewrite rule, so missing paths would match the 404 wildcard only.

I might not have understood your case completely, but, here are my 2 cents:

Sadly, Netlify reads the redirects file from top to bottom. After 1st match is found, rest is ignored. So, in your case after the redirect to index.json is done, the rest of the rules get ignored.

That’s what I assumed was happening. Once Netlify matches a rule, it just uses that redirect irregardless of whether where it’s pointing to exists or not.

That’s useful confirmation. It sounds like I’ll need a workaround that involves redirects that are more specific (as this kind of broad wildcard matching catches everything, files that may or may not exist in the build).

@jimniels Glad you got this working, but in my experience splats don’t work anywhere but at the end of the URL. For mid-URL wildcards, you must use placeholders.

1 Like