Skip to content

Instantly share code, notes, and snippets.

@luebster
Created May 2, 2019 19:53
Show Gist options
  • Save luebster/2ec2e6a31c24dc3e5e97a5a907ffbbf9 to your computer and use it in GitHub Desktop.
Save luebster/2ec2e6a31c24dc3e5e97a5a907ffbbf9 to your computer and use it in GitHub Desktop.
ASP.NET CORE SubdomainRedirect
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// add this somewhere in your configure method
app.UseRewriter(new RewriteOptions()
.Add(new SubdomainRedirectRule())
.AddRedirectToWwwPermanent()
);
}
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Net.Http.Headers;
namespace Redirect.library
{
public class SubdomainRedirectRule : IRule
{
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
// if host contains m., redirect;
var subdomain = GetSubDomain(request);
if (!string.IsNullOrEmpty(subdomain) && subdomain == "m")
{
var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status301MovedPermanently;
response.Headers[HeaderNames.Location] = "https://www.yourdomain.com" + request.PathBase + request.Path + request.QueryString;
context.Result = RuleResult.EndResponse;
}
}
private static string GetSubDomain(HttpRequest request)
{
string host = request.Host.Value;
if (host.Split('.').Length > 1)
{
int index = host.IndexOf(".");
return host.Substring(0, index);
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment