S
S
Sneiksus2020-09-20 17:58:37
ASP.NET
Sneiksus, 2020-09-20 17:58:37

Regex to validate www in address bar?

I want to write AddRedirect to redirect from www to non-www. What regular expression can I use to check if the url contains www. ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FreeBa, 2020-09-21
@Sneiksus

If we are talking about asp.net core, then you can use middleware. Something like this:

public class RedirectToNoWwwRule : IRule
{
    public virtual void ApplyRule(RewriteContext context)
    {
        var req = context.HttpContext.Request;
        if (req.Host.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase))
        {
            context.Result = RuleResult.ContinueRules;
            return;
        }

        if (!req.Host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
        {
            context.Result = RuleResult.ContinueRules;
            return;
        }

        var NoWwwHost = new HostString(req.Host.Value.Substring(4));
        var newUrl = UriHelper.BuildAbsolute(req.Scheme, NoWwwHost , req.PathBase, req.Path, req.QueryString);
        var response = context.HttpContext.Response;
        response.StatusCode = 301;
        response.Headers[HeaderNames.Location] = newUrl;
        context.Result = RuleResult.EndResponse;
    }
}

Then we create an extension method
public static class RewriteOptionsExtensions
{
    public static RewriteOptions AddRedirectNoWww(this RewriteOptions options)
    {
        options.Rules.Add(new RedirectToNoWwwRule());
        return options;
    }
}

and then we write in Startup.cs in Configure
var options = new RewriteOptions();
options.AddRedirectNoWww();
app.UseRewriter(options);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question