.NET MVC 2 RequireHttps - How to redirect www.mysite.com to mysite.com

时间秒杀一切 提交于 2020-01-05 09:53:06

问题


In .NET MVC 2 you can apply the <RequireHttps()> attribute to make a method be secured by SSL.

<RequireHttps()>
Function Index() As ActionResult
    Return View()
End Function

Let's say that your SSL certificate is issued for mysite.com. If the user visits your site by entering http://www.mysite.com, <RequireHttps()> will redirect them to https://www.mysite.com, which would make the browser display an invalid certificate warning.

What is the best way to chop off the www. prefix when using <RequireHttps()> ?


回答1:


The solution is to always (as in when the user first goes to the www version) redirect the user to non-www version of your site. So your requires Https attribute will work.

You can do this in IIS, see here: http://forums.iis.net/t/1154053.aspx




回答2:


I'm on IIS 7 and have access to the URL Rewrite module http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/.

I solved this by putting this in the web.config file of the MVC 2 application:

<configuration>
...
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="CanonicalHostNameRuleMain" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAny">
            <add input="{HTTP_HOST}" pattern="^mysite\.com$" negate="true" />
            <add input="{HTTPS}" pattern="^off$" />
          </conditions>
          <action type="Redirect" url="https://mysite.com/{R:1}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>


http://mysite.com -> https://mysite.com
http://www.mysite.com -> https://mysite.com
https://www.mysite.com -> https://mysite.com

This is simple and it works, but it would still be nice to have some sort of elegant MVC only solution.



来源:https://stackoverflow.com/questions/4066313/net-mvc-2-requirehttps-how-to-redirect-www-mysite-com-to-mysite-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!