using Microsoft.AspNetCore.Rewrite; using System.Text.RegularExpressions; // the normal AddRedirect only rewrite the rule and loses the matches // new RewriteOptions().AddRedirect("/test/(.*)","/handletest") // if they're not in the redirect itself like // new RewriteOptions().AddRedirect("/test/(.*)","/handletest/$1") // RegexRewriteWithCapture captures the first match and redirects. // it does not support matches in target url like $1, $2 ... namespace RewriteRuleServerVariable.Configuration { public class RegexRewriteWithCapture : IRule { private readonly Regex _rule; private readonly string _redirect; public RegexRewriteWithCapture(string regexRule, string redirect) { _rule = new Regex(regexRule, RegexOptions.Compiled); _redirect = redirect; } public void ApplyRule(RewriteContext context) { var request = context.HttpContext.Request; var match = _rule.Matches(request.Path.Value); if (match.Count > 0) { var response = context.HttpContext.Response; context.Result = RuleResult.SkipRemainingRules; context.HttpContext.Items.Add(nameof(RegexRewriteWithCapture), match[0].Value); context.HttpContext.Request.Path = _redirect; } } } }