Jun 1, 2022
(3 votes)

Create a Custom 404 Error Page in CMS 12

This will be my first post, rushed it out when I saw a fellow developer asked about it. Cheers!


While errors can be frustrating for website visitors, they can also provide valuable insights into how the website is being used and what needs to be improved. Error pages can be used to track down broken links, identify missing content, and diagnose other issues.

Optimizely can be used to create custom error pages that can help website owners troubleshoot issues and improve the overall user experience. This article will explain how to create a custom 404 error page using Optimizely.

Handling Exceptions in ASP.NET Core

In order to get ASP.NET Core to handle exception pages, the configuration part of the application needs to setup `UseExceptionHandler`. It is important to remember to use a condition for the development environment when developing, so that the developer exception page is still accessible.

Startup.cs : Configure

if (env.IsDevelopment())


The `UseStatusCodePagesWithReExecute` middleware returns the original status code to the client, and generate the response body by re-executing the request pipeline using an alternate path. This means that the URL in the address bar will be the same as what the browser requested.

Status code controller

The fact that the middleware is re-executing the original request means that the MVC controller logic is invoked again. This could potentially cause another error to occur, if, for example, the original request was annotated with `[HttpGet]`.

To avoid this problem, do not restrict your error handling endpoint to a specific set of HTTP methods.

public class StatusCodeController : Controller
    private readonly IContentLoader _contentLoader;

    public StatusCodeController(
        IContentLoader contentLoader)
        _contentLoader = contentLoader;

    public IActionResult Index(string statusCode)
        var statusCodePage = _contentLoader.GetBySegment(ContentReference.StartPage, statusCode, new LoaderOptions());

        if (statusCodePage is null)
            return View(statusCode);

        return new FilterContentForVisitor().ShouldFilter(statusCodePage)
            ? View(statusCode)
            : View(statusCodePage.GetOriginalType().Name, statusCodePage);

The conversion here is that every status code re re-executed against `StatusCodeController`. It takes `statusCode` as a parameter. We will look for a content page in Optimizely under the start page with the name of the status code.

If we find a the page we check that it is actually published and ready to be displayed. Pass the content to a view that handles the content model. Otherwise we will fallback to a more "static" razor page `{statusCode}.cshtml`. 

In this senario it is based on feature folder structure:

├─ 404.cshtml
├─ 500.cshtml
├─ NotFoundPage.cs
├─ NotFoundPage.cshtml
├─ NotFoundPageController.cs
├─ StatusCodeController.cs

404, Not found page

`NotFoundPage` is a page type that is used when a user tries to access a page that does not exist. This page type can be customized to include any desired properties. Some tips for customization include overriding the `PageName` to the status code so that the page gets the right name, disabling `VisibleInMenu`, and also making it non-indexable for Search and Navigation. This can for example be done by creating an `InitalizationModule` and register a conversion in  `ContextIndexer`.

    GUID = "6391362b-8e66-4e98-82ac-60380301fc04",
    GroupName = SystemTabNames.Content,
    DisplayName = "Not found page",
    Description = "Page to display when a 404 error message occurs."
public class NotFoundPage : PageData
    [Display(Order = 100)]
    public virtual string Title { get; set; } = string.Empty;

    [Display(Order = 200)]
    public virtual string Preamble { get; set; } = string.Empty;

    [Display(Order = 300)]
    public virtual XhtmlString MainBody { get; set; } = new XhtmlString();

    [Display(Order = 400)]
    public virtual ContentArea MainContentArea { get; set; } = new ContentArea();

    public override void SetDefaultValues(ContentType contentType)
        PageName = "404";
        VisibleInMenu = false;

Create a `PageController` to handle the `NotFoundPage`. 

public class NotFoundPageController : PageController<NotFoundPage>
    public IActionResult Index(NotFoundPage currentContent)
        var isLoggedIn = HttpContext.User.Identity?.IsAuthenticated ?? false;

        return isLoggedIn
            ? View("NotFoundPage", currentContent)
            : NotFound();

We check to see if the user is authenticated so that we can display a `200 response` to be able to edit it as an editor. A regular user should get `404 response`. This part can be modified to check on roles instead if needed.

If the user is not authenticated, we pass the request to `NotFound` method and it will be handled by the regular error handling process we registered before.


This article explains how to create a custom 404 page using Optimizely. This allows for different error pages on different sites and languages. The page can be customized to your liking. Once you are happy you can publish it and share it with your visitors.



Jun 01, 2022


Please login to comment.
Latest blogs
Configured Commerce - Introduction to Long-Term Support (LTS) Releases

First off, for those who have not had a chance to meet me yet, my name is John McCarroll, and I am the Technical Product Manager for the Optimizely...

John McCarroll | Sep 29, 2023

Auto-translate with OpenAI in Optimizely CMS

You can now auto-translate content using your favorite online AI service, inside the old trustworthy Episerver.Labs.LanguageManager!

Tomas Hensrud Gulla | Sep 29, 2023 | Syndicated blog

Vulnerability in CMS 12 shell module configuration

Introduction A potential security vulnerability has been identified in Optimizely CMS 12, triggered by a certain shell module configuration. To be...

Magnus Rahl | Sep 28, 2023

AI-Assistant: The 'Change Tone' Shortcut

The AI-Assistant for Optimizely is constantly evolving, adjusting, and transforming to meet your digital needs, providing a cutting-edge advantage...

Luc Gosso (MVP) | Sep 27, 2023 | Syndicated blog

How to fix scheduled job 'Remove Abandoned BLOBs' if it keeps failing

Optimizely inlcudes a job named 'Remove Abandoned BLOBs'. This post will help you fix it if it's no longer working.

Henning Sjørbotten | Sep 26, 2023 | Syndicated blog

Optimizely Web Experimentation Metrics

Within the domain of Optimizely Web Experimentation Metrics, the emphasis is on objective key performance indicators (KPIs) selected to assess an...

Matthew Dunn | Sep 23, 2023 | Syndicated blog