Search code examples
url-rewritingkentico

How to make Kentico treat URLs as if folder doesn't exist at all?


So I have a content structure of Root -> Folder -> Content page. The natural URL for this is /foldername/pagename and I'm trying to figure out how to make it always just /pagename.

I can make /pagename redirect to /foldername/pagename but it still shows as the latter in the address bar. I mucked around with URL rewrites in the web.config and I have this:

<rule name="Content" stopProcessing="true">
    <match url="^Content/(.*)" />
    <action type="Rewrite" url="/{R:1}" />
</rule>

But it doesn't seem to do anything. Any ideas how I can setup my Kentico site to treat URLs as if /foldername doesn't exist at all?


Solution

  • Two ways to accomplish this.

    • Manually set the URL path on the page. In the Pages application, open the page, and click on the URLs tab. Populate the "Path or pattern" field with the path, e.g. /pagename

      enter image description here

    • If you aren't happy with manually setting the URL path, create a global event handler to set the correct URL path on document creation (and, perhaps, update of the document). Here's an example:

      [assembly: RegisterModule(typeof(PagePathModule))]
      public class PagePathModule : Module
      {
          public PagePathModule() : base("PagePathModule") { }
      
          protected override void OnInit()
          {
              DocumentEvents.Insert.After += DocumentInsertAfter;
          }
      
          private static void DocumentInsertAfter(object sender, DocumentEventArgs e)
          {
              var node = e.Node; // TreeNode of the created document
      
              var urlPath = "/" + node.DocumentName; // Use the document name as the path
      
              node.DocumentUseNamePathForUrlPath = false; // Ensure that a custom URL path is used
              node.DocumentUrlPath = TreePathUtils.GetSafeUrlPath(urlPath, node.NodeSiteName); // Set the document URL path
              node.Update();
          }
      }
      

      You should make sure you strip out unnecessary characters from the path.