1

By seo friendly, I am trying to use the rewrite middleware to rewrite an url to a seo friendly url, but I am not successful.

As an example, what I want to do is rewrite the url https://example.com/1 to https://example.com/test-1 and the url https://example.com/1/2 to https://example.com/test-1/test-2.

I leave the Startup and ChangeURL classes that I have made.

Startup.cs:

    public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        var options = new RewriteOptions();
        options.Rules.Add(new ChangeUrl());
        app.UseRewriter(options);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

ChangeURL.cs:

    public class ChangeUrl : IRule
{
    public void ApplyRule(RewriteContext context)
    {
        var request = context.HttpContext.Request;

        Match m1 = Regex.Match(request.Path.Value, @"^/(\d+)");
        Match m2 = Regex.Match(request.Path.Value, @"^/(\d+)/(\d+)");

        if (m1.Success)
        {
            request.Path = "/test-1";
        }
        else if (m2.Success)
        {
            request.Path = "/test-1/test-2";
        }
        context.Result = RuleResult.ContinueRules;
        return;
    }
}

I appreciate all the help you can give me.

1 Answer 1

1

As far as I know, asp.net core contains the url rewrite module which is used to url rewrite it.

More details, you could refer to below codes:

         // Add below codes into the Configure method
        var options = new RewriteOptions()
.AddRewrite(@"^(\d+)/(\d+)", "test-$1/test-$2",
    skipRemainingRules: true)
.AddRewrite(@"^(\d+)", "test-$1",
    skipRemainingRules: true);

        app.UseRewriter(options);

More details, you could refer to this artcle.

       public void ApplyRule(RewriteContext context)
        {
            var request = context.HttpContext.Request;

            Match m1 = Regex.Match(request.Path.Value, @"^/(\d+)");
            Match m2 = Regex.Match(request.Path.Value, @"^/(\d+)/(\d+)");

            if (m1.Success)
            {
                request.Path = "/home/Privacy";
            }

            if (m2.Success)
            {
                request.Path = "/home/account";
            }
           
                context.Result = RuleResult.ContinueRules;

            
            return;
        }
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry if I have not expressed myself well, actually test-1 and test-2 refer to data obtained from a database, that is, they are not static texts but correspond to the descriptions of Id's 1 and 2. For example: CatId = 4, Descript = "Fruits", ProdId = 3, Descript = "Apple" What I want is to dynamically rewrite the urls example.com/4/3 with example.com/fruits/apple where example.com/4/3 is comes from: <a asp-page="/products" asp-route-catid="4" asp-route-prodid="3"/>...</a> Due to I use a class that implement IRule to create the rules for the rewrite module.
In my opinion, this is related with your rewrite rule logic, I found you have two success and use if else logic. that means if the url paht is 1/2, that means it will never go to the second if else. I suggest you could modify it as my update answer and test again.
Yes, I have changed the logic, first I evaluate m2 and then m1 and now the flow is ok, but still the url does not change. I have tried with your updated answer and it doesn't work either.
You are using the url rewrite rule not the redirect rule logic. The rewrite rule will not change the url which shown in your browser, but it will return modified request path context.
Sorry for the delay. Indeed, rewrite middleware does not change the url in the browser. I have used another approach. I submit the product name and then generate a friendly url using route conventions. Apparently it is not possible to change parameters 1, 2, ... to their respective product names without using redirection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.