2014-02-11 118 views
0

我想將我的頁面從http重定向到https協議,但遇到困難。以下是我試過到目前爲止:http to https重定向不起作用

加入以下的Global.asax

protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
    if (!Request.IsLocal && !Request.IsSecureConnection) 
     if (HttpContext.Current.Request.IsSecureConnection || HttpContext.Current.Request.IsLocal) 
      Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl); 
} 

添加下面的每一頁

protected override void OnPreInit(EventArgs e) 
{ 
    base.OnPreInit(e); 
    if (!IsPostBack) 
     RedirectAccordingToRequiresSSL(); 
} 

private void RedirectAccordingToRequiresSSL() 
{ 
    if (!Request.IsLocal && !Request.IsSecureConnection) 
     if (!Request.IsSecureConnection) // Need to redirect to https 
      RedirectAccordingToRequiresSSL(Uri.UriSchemeHttps); 
} 

private void RedirectAccordingToRequiresSSL(string scheme) 
{ 
    var url = scheme + Uri.SchemeDelimiter + Request.Url.Authority + Request.Url.PathAndQuery; 
    Response.Redirect(url, false); 
} 

添加重寫web.config中,但我認爲重寫元素本身不能正常工作

<system.webServer> 
    <rewrite> 
     <rules> 
     <rule name="Redirect HTTP to HTTPS" stopProcessing="true"> 
      <match url="(.*)"/> 
      <conditions> 
      <add input="{HTTPS}" pattern="^OFF$"/> 
      </conditions> 
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/> 
     </rule> 
     </rules> 
    </rewrite> 

無論我嘗試什麼,輸入http://my.website.here將永遠不會重定向到https://my.website.here。我一直收到的錯誤是403(禁止)。但直接使用https輸入網址效果很好。任何幫助將不勝感激。

回答

0

我剛剛在本地嘗試過,我可以通過以下規則從http重定向到https。

enter code here 
<rule name="TO SSL" patternSyntax="Wildcard" stopProcessing="true"> 
    <match url="*" /> 
    <conditions logicalGrouping="MatchAny"> 
     <add input="{HTTPS}" pattern="Off" /> 
    </conditions> 
    <action type="Redirect" url="https://{HTTP_HOST}{URL}" /> 
</rule> 

實施例的Fiddler痕量

GET http://www.site.com/test?qs=1 HTTP/1.1 
Host: www.site.com 
Connection: keep-alive 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36 


HTTP/1.1 301 Moved Permanently 
Content-Type: text/html; charset=UTF-8 
Location: https://www.site.com/test?qs=1 
Server: Microsoft-IIS/7.5 
X-Powered-By: ASP.NET 
Date: Wed, 12 Feb 2014 01:14:49 GMT 
Content-Length: 154