Configure rewrite rules for CMS 12 applications

  • Updated

This article describes how to set up rewrite (redirect) rules for ASP NetCore and CMS 12 web application.

Rewrite rules is a feature of ASP Net. Customers and developers are required to configure themselves as this is out of Optimizely's support scope.
Please refer to Microsoft's documentation here for further guidelines and examples: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting 

Add rewrite rules in Startup code as a request pipeline

public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var rewrite = new RewriteOptions()
.AddRedirectToHttps()
.AddRedirectToWww()
.AddRedirect("regex_pattern", "replacement_string");
app.UseRewriter(rewrite);
}
}

Rewrite rules are expected to be configured right before app.UseStaticFiles() and app.UseRouting().

To add advanced rules, for example, based on HTTP header:

rewrite = rewrite.Add(ctx =>
{
var request = ctx.HttpContext.Request;
if (context.Request.Headers.ContainsKey("DNT"))
{
// Proceed do-not-track request
ctx.Result = RuleResult.EndResponse;
}
ctx.Result = RuleResult.ContinueRules;
});

Migrate IIS rewrite rules (from CMS 11 or Net Framework platform or Apache hosting):

using(StreamReader fileStreamReader = System.IO.File.OpenRead("path/to/file"))
rewrite = rewrite
.AddApacheModRewrite(fileStreamReader) // .htaccess file
.AddIISUrlRewrite(fileStreamReader); // XML-based file contains <rewrite> element

 

Because rewrite rules are fixed in code and Optimizely Support cannot help you in case a rule is not working properly. Please make sure you have tested carefully before deployment to avoid unexpected issues or infinite redirect loops.