Orchardcore url rewriting

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore url rewriting is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for configuring URL rewriting in Orchard Core. Covers redirect vs rewrite rules, regex pattern matching, Apache mod_rewrite flags, admin path exclusion, rule ordering with drag-and-drop in List and Grid admin list layouts, the ManageUrlRewritingRules permission, custom rule sources, IRewriteRu

How to use this skill

Skill file

Orchard Core URL Rewriting - Prompt Templates

Configure URL Rewriting and Redirects

You are an Orchard Core expert. Generate URL rewrite rules, redirect configurations, and custom rule sources for Orchard Core.

Guidelines

Enabling URL Rewriting

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "OrchardCore.UrlRewriting"
      ],
      "disable": []
    }
  ]
}

Available Rule Types

| Rule Type | Description | Use Case |

|-----------|-------------|----------|

| Redirect Rule | Sends an HTTP redirect response (301/302/307/308) to the client. The browser URL changes. | URL migrations, domain changes, SEO canonical URLs. |

| Rewrite Rule | Modifies the request URL server-side. The browser URL stays the same. | URL aliasing, serving content from different paths. |

Redirect Rule Properties

| Property | Description |

|----------|-------------|

| Id | Unique identifier. Leave empty to create new; match existing ID to update. |

| Name | Descriptive name for the rule. |

| Pattern | Regex pattern to match against the request URL. |

| SubstitutionPattern | Target URL for the redirect. Supports $1, $2 capture groups. |

| IsCaseInsensitive | When true, pattern matching ignores case. |

| QueryStringPolicy | Append keeps original query string; Drop discards it. |

| RedirectType | MovedPermanently (301), Found (302), TemporaryRedirect (307), or PermanentRedirect (308). |

Rewrite Rule Properties

| Property | Description |

|----------|-------------|

| Id | Unique identifier. Leave empty to create new; match existing ID to update. |

| Name | Descriptive name for the rule. |

| Pattern | Regex pattern to match against the request URL. |

| SubstitutionPattern | Target URL for the rewrite. Supports $1, $2 capture groups. |

| IsCaseInsensitive | When true, pattern matching ignores case. |

| QueryStringPolicy | Append keeps original query string; Drop discards it. |

| SkipFurtherRules | When true, no subsequent rules are processed if this rule matches. |

Redirect Type Reference

| Value | HTTP Status | Description |

|-------|-------------|-------------|

| Found | 302 | Temporary redirect. |

| MovedPermanently | 301 | Permanent redirect; clients should update bookmarks. |

| TemporaryRedirect | 307 | Temporary redirect; preserves HTTP method (POST stays POST). |

| PermanentRedirect | 308 | Permanent redirect; preserves HTTP method. |

Recipe: Create Redirect and Rewrite Rules

{
  "steps": [
    {
      "name": "UrlRewriting",
      "Rules": [
        {
          "Source": "Redirect",
          "Name": "Redirect old-page to new-page",
          "Pattern": "^/old-page$",
          "SubstitutionPattern": "/new-page",
          "IsCaseInsensitive": true,
          "QueryStringPolicy": "Append",
          "RedirectType": "MovedPermanently"
        },
        {
          "Source": "Redirect",
          "Name": "Redirect legacy blog URLs",
          "Pattern": "^/blog/post/(\\d+)$",
          "SubstitutionPattern": "/articles/$1",
          "IsCaseInsensitive": true,
          "QueryStringPolicy": "Drop",
          "RedirectType": "MovedPermanently"
        },
        {
          "Source": "Rewrite",
          "Name": "Serve media from img path",
          "Pattern": "^/img/(.*)$",
          "SubstitutionPattern": "/media/$1",
          "IsCaseInsensitive": true,
          "QueryStringPolicy": "Drop",
          "SkipFurtherRules": true
        }
      ]
    }
  ]
}

Recipe Behavior

The UrlRewriting step (requires OrchardCore.Recipes.Core) updates a rule when its Id matches an existing rule; otherwise it creates one from Source. Validation errors are reported and the rule is skipped. There is no dedicated deployment step; re-create rules from a recipe in each environment.

Custom Rule Source Implementation

using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.Localization;
using OrchardCore.UrlRewriting;
using OrchardCore.UrlRewriting.Models;

namespace MyModule.UrlRewriting;

public sealed class CustomRuleSource : IUrlRewriteRuleSource
{
    public const string SourceName = "CustomRule";

    public CustomRuleSource(IStringLocalizer<CustomRuleSource> stringLocalizer)
    {
        DisplayName = stringLocalizer["Custom rule"];
        Description = stringLocalizer["Custom URL rewrite rule"];
    }

    public string TechnicalName => SourceName;

    public LocalizedString DisplayName { get; }

    public LocalizedString Description { get; }

    public void Configure(RewriteOptions options, RewriteRule rule)
    {
        if (!rule.TryGet<CustomRuleMetadata>(out var metadata) || string.IsNullOrEmpty(metadata.Host))
        {
            return;
        }

        // Add any ASP.NET Core rewrite rule.
        options.AddRedirectToWwwPermanent(metadata.Host);
    }
}

public sealed class CustomRuleMetadata
{
    public string Host { get; set; }
}

Populating a Custom Rule from Recipes

Rule data from the recipe (or IRewriteRulesManager.NewAsync(source, data) / UpdateAsync(rule, data)) reaches your source through an IRewriteRuleHandler. Derive from RewriteRuleHandlerBase and store your metadata on the rule (RewriteRule is an Entity):

using OrchardCore.Entities;
using OrchardCore.UrlRewriting.Handlers;
using OrchardCore.UrlRewriting.Models;

namespace MyModule.UrlRewriting;

public sealed class CustomRuleHandler : RewriteRuleHandlerBase
{
    public override Task InitializingAsync(InitializingRewriteRuleContext context)
        => PopulateAsync(context.Rule, context.Data);

    public override Task UpdatingAsync(UpdatingRewriteRuleContext context)
        => PopulateAsync(context.Rule, context.Data);

    private static Task PopulateAsync(RewriteRule rule, System.Text.Json.Nodes.JsonNode data)
    {
        if (rule.Source != CustomRuleSource.SourceName)
        {
            return Task.CompletedTask;
        }

        var metadata = rule.GetOrCreate<CustomRuleMetadata>();
        var host = data[nameof(CustomRuleMetadata.Host)]?.GetValue<string>();

        if (!string.IsNullOrEmpty(host))
        {
            metadata.Host = host;
        }

        rule.Put(metadata);

        return Task.CompletedTask;
    }
}

Override ValidatingAsync to reject invalid data with context.Result.Fail(new ValidationResult(...)).

Custom Rule Display Driver

using Microsoft.Extensions.DependencyInjection;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.UrlRewriting;
using OrchardCore.UrlRewriting.Models;

namespace MyModule.UrlRewriting;

public sealed class CustomRuleDisplayDriver : DisplayDriver<RewriteRule>
{
    public override IDisplayResult Edit(RewriteRule model, BuildEditorContext context)
    {
        return Initialize<CustomRuleViewModel>("CustomRule_Fields_Edit", viewModel =>
        {
            // Populate view model from model properties.
        }).Location("Content");
    }

    public override async Task<IDisplayResult> UpdateAsync(RewriteRule model, UpdateEditorContext context)
    {
        var viewModel = new CustomRuleViewModel();
        await context.Updater.TryUpdateModelAsync(viewModel, Prefix);

        // Apply view model values to the model.

        return Edit(model, context);
    }
}

public class CustomRuleViewModel
{
    public string CustomProperty { get; set; }
}

Registering a Custom Rule Source in Startup

using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.Modules;
using OrchardCore.UrlRewriting;
using OrchardCore.UrlRewriting.Models;

namespace MyModule;

public sealed class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddRewriteRuleSource<CustomRuleSource>(CustomRuleSource.SourceName)
            .AddScoped<IRewriteRuleHandler, CustomRuleHandler>()
            .AddScoped<IDisplayDriver<RewriteRule>, CustomRuleDisplayDriver>();
    }
}

Common Redirect Patterns

| Scenario | Pattern | Substitution | Type |

|----------|---------|--------------|------|

| Exact page redirect | ^/about-us$ | /about | MovedPermanently |

| Path prefix redirect | ^/old-blog/(.*)$ | /blog/$1 | MovedPermanently |

| Trailing slash removal | ^(.+)/$ | $1 | MovedPermanently |

| Legacy ID to slug | ^/post/(\\d+)$ | /articles/$1 | MovedPermanently |

Common Rewrite Patterns

| Scenario | Pattern | Substitution | SkipFurtherRules |

|----------|---------|--------------|------------------|

| Media alias | ^/img/(.*)$ | /media/$1 | true |

| API versioning | ^/api/v1/(.*)$ | /api/v2/$1 | true |

| Clean URLs | ^/page/(.*)$ | /content/$1 | false |

Upgrading from 3.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.