【问题标题】:Redirect certain pages from HTTPS to HTTP将某些页面从 HTTPS 重定向到 HTTP
【发布时间】:2014-03-19 17:33:54
【问题描述】:

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:"));
            }
        }

现在,如果请求非 https 的“安全”页面,它会执行我想要的操作,它会 301 到 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)**

【问题讨论】:

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


【解决方案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 协议的操作/控制器中

【讨论】:

  • 不确定这在我的情况下是否有效,因为有问题的控制器根据 EPiServer 页面类型提供任意数量的 URL。因此,我无法为我的操作添加属性。 .
猜你喜欢
  • 1970-01-01
  • 2011-10-12
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 2016-12-12
  • 2011-01-30
  • 1970-01-01
相关资源
最近更新 更多