【问题标题】:ASP.NET Core url rewrite only domainASP.NET Core url 仅重写域
【发布时间】:2023-03-28 22:05:02
【问题描述】:

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

当我请求时:

www.myolddomain.net/article/seo-friendly-url-for-this-article

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

www.mynewdomain.com/article/seo-friendly-url-for-this-article

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

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 在不了解您的情况的情况下,我建议您使用状态码 301 和 Location 标头 see MDN 进行响应
  • 使用状态码 307 进行临时重定向,使用 301 进行永久重定向(浏览器会记住)
  • @hatef - 你试过下面的方法吗?告诉我进展如何。

标签: asp.net-core url-rewriting .net-core asp.net-core-2.2


【解决方案1】:

你考虑过URL Rewriting Middleware吗?

这很简单。

  1. 将 IISUrlRewrite.xml 文件拖放到应用程序文件夹的根目录中。将其标记为“内容”并将“复制到输出目录”设置为 true,在您的 csproj 中看起来像这样
  <ItemGroup>
    <Content Include="IISUrlRewrite.xml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  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>
  1. Startup.cs 文件的 Configure 方法中注册 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
}

【讨论】:

    猜你喜欢
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 2012-01-03
    • 2018-12-24
    相关资源
    最近更新 更多