2017-04-14 81 views
1

我想重定向我的網站從www到非www規則以及http到https(https://example.com)在中間件中。我用來做在web.config的重定向變化,如:ASP.NET核心URL重寫

<rewrite> 
    <rules> 
    <clear /> 
    <rule name="Redirect to https" stopProcessing="true"> 
     <match url=".*" /> 
     <conditions> 
     <add input="{HTTPS}" pattern="off" ignoreCase="true" /> 
     </conditions> 
     <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" /> 
    </rule> 
    <rule name="Redirects to www.domain.com" patternSyntax="ECMAScript" 
      stopProcessing="true"> 
     <match url=".*" /> 
     <conditions logicalGrouping="MatchAny"> 
      <add input="{HTTP_HOST}" pattern="^example.com$" /> 
     </conditions> 
     <action type="Redirect" url="https://www.example.com/{R:0}" /> 
    </rule> 

我是新來asp.net的核心,並想知道我怎樣才能讓我的中間件的重定向?我讀了這篇文章:但它並沒有幫助我強制我的www重定向到非www。

回答

2

安裝下面的NuGet包:

Microsoft.AspNetCore.Rewrite 

添加以下行:

app.UseCustomRewriter(); 

內:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 

調用.UseMvc方法之前。

而下面的擴展類添加到您的項目:

public static class ApplicationBuilderExtensions 
{ 
    public static IApplicationBuilder UseCustomRewriter(this IApplicationBuilder app) 
    { 
     var options = new RewriteOptions() 
      .AddRedirectToHttpsPermanent() 
      .AddPermanentRedirect("(.*)/$", "$1"); 

     return app.UseRewriter(options); 
    } 
} 

在RewriteOptions您可以提供重寫的配置。

箍這將幫助你。

此致敬禮, 科林

+0

非常感謝! – Huby03