Return a 404 Not Found for invalid Sitecore item

Posted 01/15/2014 by Emer Kurbegovic

In the event where Sitecore cannot find the item requested, user can be redirected to the 404 Not Found page

which can be configured in ItemNotFoundUrl setting.

Instead of having Sitecore use the 302 redirect to get to the 404 page we are going to instead use the

pipeline to determine when Sitecore item doesn't exist, request the contents of the 404 page and then return

those contents as well as setup the proper 404 Not Found status code.

Here is the code:

public class ExecuteRequest : Sitecore.Pipelines.HttpRequest.ExecuteRequest
    protected override void RedirectOnItemNotFound(string url)
        var context = System.Web.HttpContext.Current;
            // NotFound page html content
            string domain = context.Request.Url.GetComponents(UriComponents.Scheme |
            UriComponents.Host, UriFormat.Unescaped);
            string content = Sitecore.Web.WebUtil.ExecuteWebPage(string.Concat(domain,
            // set Response params
            context.Response.TrySkipIisCustomErrors = true;
            context.Response.StatusCode = 404;
            context.Response.StatusDescription = "Page not found";
            // write out NotFound page html content
        catch (Exception)
            // In case of a problem use the default method
        // Sends all buffered output to the client, stops execution of the page, and raises
        the EndRequest method.

Do not forget to edit the configuration file to include your new pipeline.

<processor type="Sitecore.Pipelines.HttpRequest.ExecuteRequest, Sitecore.Kernel">
  <patch:attribute name="type" value="[PROJECT_NAME].Pipelines.ExecuteRequest, [PROJECT_NAME]" />