ASP.NET Core url 仅重写域

Hat*_*ef. 2 url-rewriting .net-core asp.net-core asp.net-core-2.2

我正在尝试将旧域更改为新域,并且我的网站上有大量数据。我只需要通过 url 重写来更改我的域。

当我请求时:

www.myolddomain.net/article/seo-friendly-url-for-this-article
Run Code Online (Sandbox Code Playgroud)

我需要永久(301)重定向到:

www.mynewdomain.com/article/seo-friendly-url-for-this-article
Run Code Online (Sandbox Code Playgroud)

我如何在 asp.net core 中做到这一点?

Hir*_*sai 5

您是否考虑过URL 重写中间件

这很简单。

  1. 在应用程序文件夹的根目录中放置一个 IISUrlRewrite.xml 文件。将其标记为“内容”和“复制到输出目录”设置为 true,在您的 csproj 中看起来像这样
  <ItemGroup>
    <Content Include="IISUrlRewrite.xml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
Run Code Online (Sandbox Code Playgroud)
  1. 在文件中添加以下内容
<rewrite>
  <rules>    
    <rule name="Host replace - Old to new" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="www\.myolddomain\.net" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://www.mynewdomain.com{REQUEST_URI}" redirectType="Permanent" appendQueryString="true" />
    </rule>
   </rules>
</rewrite>
Run Code Online (Sandbox Code Playgroud)
  1. Configure你的Startup.cs文件的方法中注册URL重写模块
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{   
    // Irrelevant code omitted

    using (var iisUrlRewriteStreamReader = File.OpenText(Path.Combine(env.ContentRootPath, "IISUrlRewrite.xml")))
    {
        var options = new RewriteOptions().AddIISUrlRewrite(iisUrlRewriteStreamReader);
        app.UseRewriter(options);
    }

    // Irrelevant code omitted
}
Run Code Online (Sandbox Code Playgroud)