0

I have a solution writted in C# in VS2010. When I type http://www.mywebsite.com in my browser, I am able to display my website successfully. When I type http://mywebsite.com in my browser, I am able to display my website but with some CSS problems. Because in my code I have some settings file where my website is recognised as 'http://www.mywebsite.com'. That's the story.

My question is: if user is typing http://mywebsite.com is there a way to redirect to http://www.mywebsite.com?

For example, if you type http://google.com it is automatically redirected to http://www.google.com

Thanks.

Bronzato
  • 9,438
  • 29
  • 120
  • 212
  • 1
    possible duplicate of [IIS 7 Canonical URL redirect](http://stackoverflow.com/questions/5857118/iis-7-canonical-url-redirect) – Daniel A. White Feb 02 '12 at 16:26

2 Answers2

0

Add this to web.config:

<rewrite>
<rules>
    <rule name="Redirect mywebsite.com to www" patternSyntax="Wildcard" stopProcessing="true">
        <match url="*" />
        <conditions>
            <add input="{HTTP_HOST}" pattern="mywebsite.com" />
        </conditions>
        <action type="Redirect" url="http://www.mywebsite.com/{R:0}" />
    </rule>
</rules>
</rewrite>

In code-behind, you can also use something like (not tested)

if(!Request.Url.Host.StartsWith("www"))
    Response.Redirect("http://www.mysite.com/" + Request.Url.LocalPath);

but that would have to be on every page on on the MasterPage (if you have one) or slightly altered in Global.asax

Olaf
  • 10,049
  • 8
  • 38
  • 54
  • It works, thank you. But I got a warning in my web.config on the rewrite word telling me: "The element 'system.webserver' has invalid child element 'rewrite'". Anything to do to avoid this warning? – Bronzato Feb 02 '12 at 16:54
  • The particular configuration section is not known by your system. Check http://stackoverflow.com/questions/5309059/the-element-system-webserver-has-invalid-child-element-rewrite or google for the error message. The correct tags depend on your .NET version (it's different in 4, I believe) and/or on your IIS version. – Olaf Feb 02 '12 at 17:05
0

Check out Iirf:

http://iirf.codeplex.com/

Once installed on your server create an ini file called Iirf.ini with the following content:

RewriteEngine ON 
StatusInquiry ON RemoteOk 
RewriteCond %{HTTP_HOST} ^mywebsite.com [I] 
RedirectRule ^/(.*)$ http://www.mywebsite.com/$1 [R=301]

Copy and paste the file on your root webfolder EG: httpdocs

This will do the work.

CoderRoller
  • 1,239
  • 3
  • 22
  • 39