Sitecore – 404 for Media Items – Custom Media Request Handler

After I started exploring Sitecore HttpRequestProcessor pipeline, I came to know how powerful it is. Right from handling 404 requests to configuring redirection from Sitecore Application level, everything can be handled by patching that pipeline.(I am referring stuffs other than it’s default purpose)

Esp. In a multi-site environment where each site has a different business requirement for handling 404 or redirection, customizing this pipeline is the wide spread industry practice.

Initially I thought the same custom pipeline could be used for serving media 404 items and handling media redirects. But I was wrong. When I browsed further, I came across two solution,

  1. Patch the notfounditem url in the sitecore.config to the 404 page url.

This works like a charm if you want all the websites in the Sitecore instance to be redirected to a same 404 page.

But in most of the cases, we need to redirect them to different 404 pages based on the site.

   2.  Just like the custom httprequestprocessor, we need some thing that checks if the media item is present in the sitecore or not and then redirect to site specific 404 pages.

Before going into the solution, let’s see why the custom pipeline is not working for the media items.

Sitecore handles media requests separately. If it’s a media request, before the request even hits, the sitecore HttpRequestProcessor, it is passed to the Sitecore Media Request Handler. Which processes the media request and provides a response. Meaning, if the request is for a Sitecore Media item, the request wont even be passed through the custom pipeline.

Say, your media request is, http://cms.mark3.com/-/media/mark3/Ronaldo.jpg

Sitecore converts the ~ or – to sitecore and media to media library and then removes the extensions if any

So that your request becomes http://cms.mark3.com/sitecore/media library/mark3/Ronaldo

Sitecore then finds the Media item via the path (/sitecore/media library/mark3/Ronaldo) and serves the media (images/pdfs/docs or etc)

So, now to the solution. We need to create a custom media request handler and handle the site specific 404 media request logic there. Even for a media request redirection, we need to handle via the same.

In this case, we have to create a class that extends Sitecore MediaRequestHandler and handle our business logic there.

Once the class is created, we need to make update the MediaRequestHandler setting in web.config. Since this change needs to be done in web.config, it can’t be patched like other sitecore-configuration.

Update the sitecore_media.ashx type from default one to the created class/namespace.

Similarly in the same class we can add logic to handle redirection for Sitecore Media Items as well.

Leave a comment

Design a site like this with WordPress.com
Get started