Google 对于要索引哪个页面感到困惑,尽管站点地图中对此进行了很好的解释。
我在 web.config 中创建了一个重定向规则,将流量从 bare 重定向到 www,效果很好
<rule name="Redirect to www" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTP_HOST}" pattern="example.com" />
</conditions>
<action type="Redirect" url="https://www.example.com/{R:0}" redirectType="Permanent" />
</rule>
我正在尝试创建第二条规则以将domain/home/index 和domain/index 重定向到root,但我无法做到。下面不行。我在模式字段中尝试了一些使用不同正则表达式的变体,但没有任何效果。
<rule name="Redirect index" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTP_HOST}" pattern="example.com/home/index" />
</conditions>
<action type="Redirect" url="https://www.example.com/" redirectType="Permanent" />
</rule>
最佳答案
在 ASP.NET Core(MVC6) 中,我们可以使用自定义的中间件
来实现这一点。
这是一个简单的演示供您引用。
首先,创建一个Middle Ware
类。根据您的要求,我为您创建了如下:
using ASPNETCore.Test;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ASPNETCore.Middleware
{
public class MyMiddleware
{
private RequestDelegate _nextDelegate;
private IServiceProvider _serviceProvider;
public MyMiddleware(RequestDelegate nextDelegate, IServiceProvider serviceProvider)
{
_nextDelegate = nextDelegate;
_serviceProvider = serviceProvider;
}
public async Task Invoke(HttpContext httpContext)
{
string requestURL = httpContext.Request.Path.ToString().ToLower();
//redirect domain/home/index and domain/home to domain
if (requestURL.Contains("/home/index")||requestURL.EndsWith("/home"))
{
httpContext.Response.Redirect("/");
}
// redirect domain/home/something to domain/something
else if (requestURL.Contains("/home/"))
{
Regex reg = new Regex("/home/(.+)");
Match match = reg.Match(requestURL);
string value = match.Groups[1].Value;
httpContext.Response.Redirect("/"+ value);
}else{
await _nextDelegate.Invoke(httpContext);
}
}
}
}
然后我们可以在 Startup
类的 Configure
方法中使用它,如下所示:
我已经测试过它并且有效。希望这会有所帮助。
关于asp.net-mvc - Azure ASP.Net Core 网站中的 301 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52021944/