You will need to have a custom processor in the <httpRequestBegin>
which see if the item in the url is valid or not.
So, the patch will be as follows:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<httpRequestBegin>
<processor type="YourNamespaceHere, YourAssemblyHere"
patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']"/>
</httpRequestBegin>
</pipelines>
</sitecore>
</configuration>
Basically, what you need to do is to see first if the request url contains elements which should be neglected. Then, you need to see if the Context.Item
is null
. If it is null
, therefore it should redirect to the Error 404. So, the code will look something as below:
public class NotFoundProcessor : HttpRequestProcessor
{
#region Fields
private static readonly List<string> UrlsToIgnoreByCustomProcessors = new List<string> { "/sitecore/", "/sitecore", "/layouts", "/layouts/", "/error500.aspx" };
#endregion
public override void Process(HttpRequestArgs args)
{
if (UrlsToIgnoreByCustomProcessors.Any())
{
foreach (var urlsToIgnore in UrlsToIgnoreByCustomProcessors)
{
if (HttpContext.Current.Request.Url.PathAndQuery.ToLower().Contains(urlsToIgnore))
{
return;
}
}
}
//Check if Context Item is null
if(Sitecore.Context.Item != null)
{
return;
}
//Get Path of Error 404 item from Site Definition
var error404ItemPath = Sitecore.Context.Site.Properties["notFoundPageItemPath"];
var database = GetDatabase();
//Get Error 404 item from Sitecore
var error404Item = database.GetItem(error404ItemPath);
//Generate url for Error 404 item
var itemUrl = LinkManager.GetItemUrl(error404Item).Replace(context.DomainName, string.Empty);
//Perform Redirection
HttpContext.Current.Server.TransferRequest(string.Format("~/{0}?status=404", itemUrl.TrimStart('/')));
HttpContext.Current.ApplicationInstance.CompleteRequest();
return;
}
protected virtual Database GetDatabase()
{
return Context.ContentDatabase ?? Context.Database;
}
}
You will be able to add presentation to show some content to the Error 404 item.
Note: It is recommended to add caching so that it will not each time go and fetch the item in the Sitecore database. For more information, you may check the following link
locations