How to force example.com to be redirected to www.example.com with URL rewriting in IIS7? What kind of rule should go into the web.config? Thanks.
A rewrite rule defines the logic of what to compare or match the request URL with, and what to do if the comparison is successful. Rewrite rules consists of the following parts: Pattern – The rule pattern is used to specify either the regular expression or a wildcard pattern that is used to match URL strings.
Rewrite rules is a powerful feature in IIS. Common tasks like redirecting www to non-www (or the other way around), implementing canonical URLs, redirecting to HTTPS, and similar tasks are documented right there in your Web. config file.
To make it more generic you can use following URL Rewrite rule which working for any domain:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Add WWW" stopProcessing="true"> <match url="^(.*)$" /> <conditions> <add input="{HTTP_HOST}" pattern="^(?!www\.)(.*)$" /> </conditions> <action type="Redirect" url="http://www.{C:0}{PATH_INFO}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer>
This is Microsoft's sample for URL Rewrite Module 2.0 that redirects *.fabrikam.com to www.fabrikam.com
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Add www" patternSyntax="Wildcard" stopProcessing="true"> <match url="*" /> <conditions> <add input="{HTTP_HOST}" pattern="www.fabrikam.com" negate="true" /> </conditions> <action type="Redirect" url="http://www.fabrikam.com/{R:1}" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
Not sure about the best possible way to do this, but I have a site with all old domains / subdomains running this web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Transfer" stopProcessing="true">
<match url=".*" />
<action type="Redirect" url="http://www.targetsite.com/{R:0}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Seems to get the job done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With