404 redirects for file extensions... possible?

I want to redirect 404 error pages for a specific file type (or multiple file types). In this specific case, I want to redirect all images that are not found to a default image (placeholder).

What I tried without success was a redirect rule in my _REDIRECTS file like this:

*.jpg               /                     404   

I tried it before and after the “common” 404 rule without success.

How would I achieve this? I wonder if it’s possible to somehow have a redirect rule that catches regular expressions?

I feel this might be solvable via edge functions, but I have no idea how to check for the “missing” (404) state and if that may be overkill and will slow down the website/delivery of files.

Any suggestions or experiences with this topic?

You can solve this via Functions. Edge Functions can also handle this but to me, Functions look a but easier for this use-case.

import type {Config} from '@netlify/functions'

export default async function() {
  return new Response('<html><!-- The HTML for your 404 page goes here --></html>', {
    headers: {
      'content-type': 'text/html',
      'netlify-cdn-cache-control': 'durable, immutable, max-age=31536000, public' /* assuming you'd need caching for this */
    },
    status: 404
  })
}

export const config : Config = {
  pattern: '^.*\\.[Jj][Pp][Gg]$', /* RegEx to match the extension in a case-insensitive manner */
  preferStatic: true
}

The reason I suggested Functions is because of the preferStatic option. Using that, the Function would only trigger if no static file is matched. But if you want to solve it with Edge Functions (to cut costs, as Edge Functions are cheaper), you could have:

import type {Config, Context} from '@netlify/edge-functions'

export default async function(req : Request, context : Context) {
  const res = await context.next()
  if (res.status === 404) {
    return new URL('/404-jpeg.html', req.url) /* You could either return a HTML file like above, or simply send a rewrite */
    /* The following can be used if you wish to change the response headers of the `/404-jpeg.html`
    const res_404 = await context.next(new URL('/404-jpeg.html', req.url))
    return new Response(res_404.body, {
      headers: {
        'content-type': 'text/html',
        'netlify-cdn-cache-control': 'durable, immutable, max-age=31536000, public'
      },
      status: 404
    })*/
  }
}

export const config : Config = {
  cache: 'manual',
  pattern: '^.*\\.[Jj][Pp][Gg]$'
}

To summarise, here are some benefits of either option to consider:

  • Functions:

    • preferStatic is built-in, so you don’t have to check it yourself
  • Edge Functions:

    • Cheaper
    • Can rewrite to a URL instead of responding with a HTML file

Note: I haven’t tested the above code (wrote it directly in the text ecidor in the forums), but it should work for the most part.

1 Like

Hi @hrishikesh, this is a splendid answer as always… I need some time to test this out though and will mark your response as solution once I got it going on my side.

1 Like