Sanjay Kumar
Jun 21, 2024
  1075
(2 votes)

Remove a segment from the URL in CMS 12

Problem: I have created thousands of pages dynamically using schedule jobs with different templates (e.g. one column, two columns, etc..) and stored them under one of the specific container page templates but some of the page’s URLs were renamed.

So, I have two problems:

  1. How to ignore the container page name segment from the URL,
  2. Redirect to the new page without using any Add-ons or mapping the old one to the new URL.

Page Hierarchy

Name in URL

New URL (simple address url)

Expected result

Start Page -> Container Page -> One col page

study

students/study

- Remove the ‘container-page’ segment from URL.

- Apply 301 redirection for New URLs without adding any Add-Ons

https://local.alloy.com/container-page/study

 https://local.alloy.com/students/study

https://local.alloy.com/study

https://local.alloy.com/students/study

Solution: To fix the above problem we need to add the simple address for new URLs in each page and implement custom 301 redirections.

Register middleware into startup.cs file to bypass the container page segment from the URL

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration)
 {
      app.UseMiddleware<SkipContainerPageMiddleware>();
 }

Create the container page middleware to read the simple address and apply 301 redirection:

public class SkipContainerPageMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ISettingsService _settingsService;
    private readonly IContentLoader _contentLoader;

    public SkipContainerPageMiddleware(RequestDelegate next, ISettingsService settingsService, IContentLoader contentLoader)
    {
        _next = next;
        _settingsService = settingsService;
        _contentLoader = contentLoader;
    }

    public async Task Invoke(HttpContext context)
    {
       //Create a content reference type property in GlobalPageSettings or HomePage to read the container page location where all pages created
        var folderLocation = _settingsService.GetSiteSettings<GlobalPageSettings>()?.OEmbedFolderLocation ?? ContentReference.EmptyReference; 
        var folderName = "/" + _contentLoader.Get<IContent>(folderLocation).Name;

        if (context.Request.Path.StartsWithSegments(folderName, StringComparison.OrdinalIgnoreCase))
        {
            context.Request.Path = context.Request.Path.HasValue
                ? context?.Request?.Path.Value.Substring(folderName.Length)
                : string.Empty;

            if (context != null)
            {
                var url = GetSimpleAddress(folderName, context);
                if (url != null)
                {
                    var newURl = $"{context.Request.Scheme}://{context.Request.Host}/{url.Trim('/')}";
                    context.Response.Redirect(newURl, true);
                    return;
                }
            }
        }

        if (context != null)
            await _next(context);
    }

    private string? GetSimpleAddress(string parentSegment, HttpContext context)
    {
        var parentPage = _contentLoader
            .GetChildren<ContainerPage>(ContentReference.StartPage)
            .FirstOrDefault(x => string.Equals(parentSegment.Trim('/'), x.URLSegment, StringComparison.InvariantCultureIgnoreCase))?
            .ContentLink
            ?? ContentReference.EmptyReference;

        var url = context.Request.Path.HasValue ? context?.Request.Path.Value.Trim('/') : string.Empty;
        if (string.IsNullOrWhiteSpace(url) || parentPage == ContentReference.EmptyReference)
            return default;

        PageData? page = null;
        foreach (var item in url.Split('/'))
        {
            page = RecursivePageBySegment(parentPage, item);
            if (page != null)
                parentPage = page.ContentLink;
        }

        return page?.ExternalURL ?? url;
    }

    private PageData? RecursivePageBySegment(ContentReference parentPage, string urlSegment)
    {
        var children = _contentLoader.GetChildren<PageData>(parentPage);
        if (children.Count() == 0)
        {
            return _contentLoader.Get<PageData>(parentPage);
        }

        var page = children.FirstOrDefault(page => page.URLSegment.Equals(urlSegment, StringComparison.OrdinalIgnoreCase));
        return page ?? default;
    }
}

I hope this blog helps you achieve similar type functionality!

 

Jun 21, 2024

Comments

Please login to comment.
Latest blogs
How to add an Admin Mode add-on in Optimizely CMS12

How to add a new add-on with navigation and unified stylesheet

Bartosz Sekula | Jan 2, 2025 | Syndicated blog

Managing Your Graph Conventions

Recently, Optimizely released a Conventions API for manging how various fields on your CMS content are indexed by the Graph. This is an extremely...

Ethan Schofer | Dec 31, 2024

SaaS CMS and Visual Builder - Opticon 2024 Workshop Experience

Optimizely is getting SaaSy with us…. This year Optimizely’s conference Opticon 2024 took place in San Antonio, Texas. There were a lot of great...

Raj Gada | Dec 30, 2024

Copy Optimizely SaaS CMS Settings to ENV Format Via Bookmarklet

Do you work with multiple Optimizely SaaS CMS instances? Use a bookmarklet to automatically copy them to your clipboard, ready to paste into your e...

Daniel Isaacs | Dec 22, 2024 | Syndicated blog