最近因为一个需要,要将一级域名统一重定向到www. 查了一圈。网上都是www 到 一级主域名的。拿来改造一下。这里记录一下,以备查阅
这里使用.netcore 自带的Microsoft.AspNetCore.Rewrite 来做重写,直接上代码
namespace WaterMark.Code
{
public class GoToWWW : IRule
{
public void ApplyRule(RewriteContext context)
{
var req = context.HttpContext.Request;
var currentHost = req.Host;
var domain = "pysga.xyz";//var domain = "192.168.0.106:8888";
if (req.Scheme.Equals("http") && currentHost.Value == domain)
{
context.HttpContext.Response.Redirect("http://www.pysga.xyz" + req.PathBase + req.Path + req.QueryString);
context.Result = RuleResult.EndResponse;
}
//或者:
// if (currentHost.Value == domain)
// {
// context.HttpContext.Response.Redirect("http://www.pysga.xyz");//这里没有带上相关参数
// context.Result = RuleResult.EndResponse;
// }
}
}
public static class RewriteOptionsExtensions
{
public static RewriteOptions RedirectToWWW(this RewriteOptions options)
{
options.Rules.Add(new GoToWWW());
return options;
}
}
}
最后在startup.cs中注入
app.UseHttpsRedirection().UseRewriter(new RewriteOptions().RedirectToWWW());