我想将我的网页从http重定向到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直接键入URL非常有用。任何帮助将不胜感激。
答案 0 :(得分: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 Trace
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