.NET MVC 2 RequireHttps - How to redirect www.mysite.com to mysite.com
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.mysit开发者_如何学编程e.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()>
?
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
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.
精彩评论