将某些页面从HTTPS重定向到HTTP

时间:2014-02-19 11:49:37

标签: asp.net-mvc-4 redirect iis-7 http-status-code-301 episerver

Google已经使用HTTPS和HTTP索引了我们的部分网页。我想将不应该使用HTTPS的网页重定向回HTTP(301)。

这是一个EPiServer 7站点,但实际上是MVC。

我的控制器中有以下内容..

            if (currentPage.RequireSsl != null && currentPage.RequireSsl.Value && !HttpContext.Request.IsSecureConnection)
        {
            if (HttpContext.Request.Url != null)
            {
                return this.RedirectPermanent(HttpContext.Request.Url.ToString().Replace("http:", "https:"));
            }

        }
        else if (HttpContext.Request.IsSecureConnection && (currentPage.RequireSsl == null || currentPage.RequireSsl.Value == false))
        {
            if (HttpContext.Request.Url != null)
            {
                return this.RedirectPermanent(HttpContext.Request.Url.ToString().Replace("https:", "http:"));
            }
        }

现在,如果非安全地请求“安全”页面,它会执行我想要的操作,它是301s到https(在fiddler中查看时)。

**GET http://domainxx.com/section/securepage/
301 Moved Permanently to https://domainxx.com/section/securepage/**

但是,如果我在HTTPS上请求非安全页面,它会重定向,但我会获得200状态代码,而不是301. Fiddler甚至没有列出直接代码:

**GET http://domainxx/section/notsecurepage/
200 OK (text/html)**

1 个答案:

答案 0 :(得分:1)

按如下方式创建新的授权过滤器。

public class CustomRequireHttpsAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        // abort if it's not a secure connection
        if (!filterContext.HttpContext.Request.IsSecureConnection) return;

        // abort if a [RequireHttps] attribute is applied to controller or action
        if (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;
        if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;

        // abort if it's not a GET request - we don't want to be redirecting on a form post
        if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) return;

        // redirect to HTTP
        string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
        filterContext.Result = new RedirectResult(url);
    }
}

然后在FilterConfig内注册,如下所示

//redirect to http protocol if RequiredHttps not assigned to the requested action
filters.Add(new CustomRequireHttpsAttribute());

您必须将[RequireHttps]添加到需要https协议的操作/控制器