Created
May 2, 2019 19:53
-
-
Save luebster/2ec2e6a31c24dc3e5e97a5a907ffbbf9 to your computer and use it in GitHub Desktop.
ASP.NET CORE SubdomainRedirect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
// add this somewhere in your configure method | |
app.UseRewriter(new RewriteOptions() | |
.Add(new SubdomainRedirectRule()) | |
.AddRedirectToWwwPermanent() | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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