簡體   English   中英

如何重定向到https並添加www。 在鏈接前面

[英]How to redirect to https and also add www. in front of the link

我正在嘗試重定向到https

我在Global.asax中使用了以下代碼

protected void Application_BeginRequest()
{
    if (!Context.Request.IsSecureConnection)
        Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
}

但是我的問題是我必須在鏈接前面添加www,即mywesite.se,並在重定向到https之后像https://mywebsite.se一樣添加,但是我想要像https://www.mywebsite.se

使用UriBuilder

var url = Context.Request.Url;
var builder = new UriBuilder(url);
builder.Scheme = "https";
if (!url.Host.StartsWith("www"))
   builder.Host = "www." + url.Host;

Response.Redirect(builder.Uri);

免責聲明:我沒有測試此代碼。

您可以在web.config添加重寫規則

<rewrite>
    <rules>
        <clear />
        <rule name="Redirect non-www OR non-https to https://www">
            <match url=".*" />
            <conditions logicalGrouping="MatchAny">
                <add input="{HTTP_HOST}" pattern="^mywebsite.se$" />
                <add input="{HTTPS}" pattern="off" />
            </conditions>
            <action type="Redirect" url="https://www.mywebsite.se/{R:0}" redirectType="Permanent"/>
        </rule>
    </rules>
</rewrite>

在這里(寫入web.config文件)

void Application_BeginRequest(object sender, EventArgs e)
{
    string lowerCaseURL = HttpContext.Current.Request.Url.ToString().ToLower();
    if (lowerCaseURL.IndexOf("http://dotnetfunda.com") >= 0) // >=  because http starts from the 0 position : )
    {
        lowerCaseURL = lowerCaseURL.Replace("http://dotnetfunda.com", "https://www.dotnetfunda.com");

        HttpContext.Current.Response.StatusCode = 301;
        HttpContext.Current.Response.AddHeader("location", lowerCaseURL);
        HttpContext.Current.Response.End();
    }
}

dotnetfunda.com替換為yourwebsitedomainname.se

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM