Scott Forsyth's Blog

Postings on IIS, ASP.NET, SQL Server, Webfarms and general system admin.

Cloud Resources

IIS Resources

IIS URL Rewrite – rewriting non-www to www

If you’re using IIS 7.0 (or 7.5), URL Rewrite is a valuable tool, well worth installing and using.

One common use of URL Rewrite is redirecting http://domain.com to http://www.domain.com.  Many people are doing this for search engine optimization (SEO) so that search engines only see the one site, rather than two sites.  The goal is to set a permanent 301 redirect.

You can download URL Rewrite from http://www.iis.net/expand/URLRewrite.  For this walkthrough and screenshots I’ll use URL Rewrite 2.0 RC1, but everything that I’ll cover also works for version 1.0 and 1.1.

URL Rewrite works at the global level, or site level (or application level for that matter).  Where you apply it is really up to how you manage your server.  Either will work for a domain name redirect like this.

You can choose to create the rules using IIS Manager, or using a text editor and updating web.config directly.  I’ll show both, starting with IIS Manager.

Let’s get started.  First, open IIS Manager and double-click on the “URL Rewrite” icon.

image

Next, click on “Add Rules…” from the Actions pane.

Here you’ll have a choice from a few wizard options, and with URL Rewrite 2.0 you can also create outbound rules.  Create a Blank rule (inbound rules).

image

Give your rule a good friendly “Name”.  I’ll call mine “Redirect domain.com to www”.

In the “Using” dropdown box you can choose between Regular Expressions and Wildcards.  Use wildcards if you aren’t familiar with regular expressions since they are much more intuitive.  However, if you later need to create more complex rules, regex may be necessary.

For this demo select WildcardsHowever, I’ll include instructions for those wanting to use regular expressions.

Enter * for the “Pattern”.  That means anything qualifies.  We’ll use a condition later instead of matching to the URL.  (for Regular Expressions, use .*).

Now expand the “Conditions” section and click “Add”.  In the “Add Condition” dialogue enter the following:

Condition input: {HTTP_HOST}
Check if input string: Matches the Pattern
Pattern: domain.com
(for regex, enter ^domain.com$)
Ignore case: checked

image

Click OK.

Finally, it’s time to set the Action.

In the Action section make sure that the “Action Type” is set to Redirect

For the “Action Properties”, enter http://www.domain.com/{R:0}.  The {R:0} retains the existing URL so if someone typed something like http://domain.com/aboutus it would retain the aboutus as it adds the www.

Note (added later): If you want this to be more generic to account for multiple domain names and to retain the original domain name in the redirect, check out this blog post.

Be sure that the “Append query string” remains checked so that the querystring part is also retained.

Also, be sure that the “Redirect Type” is set to Permanent (301), which is what the search engines like.  This tells the search engines to do a permanent redirect, use the new location and ignore the previous location.

image

Finally, Apply the rule and test!

Using a Text Editor

You can also create this rule manually by adding the following to your site’s web.config (or applicationHost.config if you set this at the server level).

In the <system.webServer> section of your web.config, add the following:

Wildcards

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

 

Save and you should be set.

Or, if you prefer Regular Expressions, use this instead:

Regular Expressions

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

This is just the start to great SEO, but it’s a common step and one that I hope you find helpful.

See Part II on how to redirect multiple domain names to a single domain name: http://weblogs.asp.net/owscott/archive/2009/11/30/iis-url-rewrite-redirect-multiple-domain-names-to-one.aspx

Also see this blog post on how to do a generic redirect while retaining the original domain name.

Posted: Nov 27 2009, 05:55 PM by OWScott | with 77 comment(s)
Filed under: , ,

Comments

r4 dsi said:

Wow it good to know that using IIS Manager there are so many new options available. I normally like my net history categorized. Yes its just a step towards great SEO.

# November 30, 2009 5:54 AM

rubens said:

If there any generic way to do that if we have multiple domains with multiple extensions?

example:

mydomain.com to www.mydomain.com (already done)

mydomain.net to www.mydomain.com

www.mydomain.net to www.mydomain.com

etccc...

and maybe also

www.mydomain2.net to www.mydomain.com

etccc...

Thanks.

# November 30, 2009 3:19 PM

OWScott said:

That's where regular expressions and multiple conditions come in.

To get you started, if you switch to regular expressions and use the example in my blog, then for the Condition Pattern, rather than ^domain.com$, switch it to ^domain.(com|net)$.  That will catch both .com and .net.

If you are redirecting them all to the same domain it's easy.  You don't need to update the Redirect URL.

If you do want to retain the .com or .net you can use {C:1} instead of com the redirect URL, but that's likely not what you're worried about.

To get mydomain2.net, just switch the Logical grouping dropdown in the conditions to "Match any" and add as many conditions as you want.  As long as any of them catch, it will redirect.

Obviously make sure that you don't put a condition that is the same as the redirect URL, otherwise you'll get a loop.

Note, you can do this with wildcards instead of regular expressions.  Just create a new condition for each of .com and .net and mydomain2.net.

# November 30, 2009 3:48 PM

rubens said:

Thanks a lot for the reply. I'm testing things right now and succeeded making it work with 8 rules.

I use only the web.config code since it's quicker.

If I want to make a rule that redirects any domain (www or non www; .net.org) to only one how would you do it?

Thanks,

# November 30, 2009 4:50 PM

OWScott said:

Hi Rubens.  I figured it would be worth answering that with a blog post where I can include screenshots: weblogs.asp.net/.../iis-url-rewrite-redirect-multiple-domain-names-to-one.aspx.  Hopefully that helps.

# November 30, 2009 5:43 PM

rubens said:

I appreciate that very much !!!!

Thanks.

# November 30, 2009 6:12 PM

nidhi tiwari said:

if we create web.config file on client's site becoz it was not there thn how can we use it for url redirection from www url to non www url and vise versa

# December 10, 2009 7:32 AM

Scott Forsyth said:

As long as your server (or host) supports URL Rewrite, then you can add the config directly to web.config in the <system.webServer> section and it should work for you.  It needs to be installed on the server for it to take though.

# December 10, 2009 9:21 AM

OWScott said:

Hi David.  My best guess is that another rule catches first and is set to stop processing.  That will prevent rules further down from working.

A good test to see if the conditions work is to set the action to a custom response code of 500 0 and Test / Test for the text.  That's a quick and easy way to confirm that it's working.  Try moving the rule to the top of the list and see if it catches then.  If it still doesn't, try a quick 'break test' by stopping the website to confirm that it's bound to that site (it sounds like it is).  Also confirm that the rule type it wildcards or regular expressions... whatever you're expecting.  Being set to the opposite as you expect could cause rules that don't work.

# February 1, 2010 6:00 PM

David Moore said:

Thanks for your help. It took reading through your examples a few more times and checking my code. Eventually I got it to work and now all my websites are humming with www redirected url's. Now on to SEO Friendly url's!? The new IIS 7(.5) is really, pretty incredible. It's just another learning curve for IT and web developers.

# February 25, 2010 4:22 PM

Mark Howell said:

You can do this without URL rewriting.  I do it this in IIS way:

Set up main site with host header for www.mydomain.com

Set up 2nd site with host header for mydomain.com

In IIS 6, In the Home Directory setting in the 2nd site properties, I tell the site to obtain content from a URL redirect to www.mydomain.com and click the option for making it a permanent redirection

In IIS 7, in the 2nd site HTTP Redirect properties, it set it to redirect to www.mydomain.com and select the option to make it a 301 permanent redirect.

I can set up a 3rd, 4th, .... nth site using different host header names, like mydomain.net, mydomain.us, etc., and configure them the same way as the 2nd site.

Then, whenever anyone uses the url for any of the 2nd or later sites, they are redirected to the first site.  

Works like a champ.

# January 26, 2011 12:32 PM

OWScott said:

Mark.  I fully agree, that works well in many situations.  Just a couple things to consider.  

Not everyone has a dedicated server.  Some people need to do this from a shared account.  So they don't have this as an option.

Some people have lots of domains so wildcard or regex rules offer more flexibility than setting up multiple IIS sites.

And some people would prefer (myself included) to use URL Rewrite rules--if they are familiar with URL Rewrite--over managing multiple redirecting sites.  It comes down to preference.

Definitely in IIS6 on a dedicated server, I agree fully.  Sometimes in IIS7 on a dedicated server, it all comes down to what people are familiar with.

# January 26, 2011 1:08 PM

chekmate111 said:

If I don't know how many numbers will be in the url can I just use * to account for all varitions?

Also, how do I add more than one rule to the Web.config? I would add the non-www to www rule and a rule that changed filename.aspx?id=11 to 11/filename.aspx

Thank you for the work you have done on this so far.  

# March 18, 2011 3:42 PM

OWScott said:

Hi chekmate111,

If your rule type is Regular Expressions, you can use \d for all digits.  Or \d{2} or \d\d to require 2 digits (for example).  .* will also work, but that gets all types of input, not just numbers.

You can add as many rules as you want.  It from the UI, just add another rule.  If from web.config, just wrap your rule in a <rule></rule> like the other one, and it will work without issue.

# March 18, 2011 4:41 PM

chekmate111 said:

OWScott thank you for your hard work!

Fundamental question: Which one of these two methods should I use?

1) write the code on my site to produce links in the form, /22/page.aspx and then redirect to page.aspx?id=22

or

2) write the link like page.aspx?id=22 and then redirect to /22/page.aspx ?

I ask because I see a lot of reference to redirecting to pagename.aspx?id=22 from 22/pagename

# March 21, 2011 11:56 AM

OWScott said:

Chekmate111,

To keep the search engines happy, you should make sure that your links on your pages (i.e. what your code generates) are in the form of /22/page.aspx.  Then do a 'rewrite' to page.aspx?id=22 using URL Rewrite.  Then the search engines are none the wiser about the page.aspx?id=22 format.  

So that's mostly your 1) option, but it's a rewrite rather than a redirect.  

You can still have a rule to redirect from page.aspx?id=22 to /22/page.aspx to catch anything that is missed in your HTML, but it's just an extra precaution.  It is a good practice though because the search engines will follow to the better URL and use that instead.

# March 21, 2011 12:15 PM

chekmate111 said:

Okay, so I think I am beginning to put this all together. I will code the links in like 22/pagename and rewrite to pagename?id=22

I will then try to redirect pagename?id=22 to 22/pagename just in case something gets overlooked.

Using your code above I believe I can redirect. Do you have a resource I could read for rewrite?

For the redirect I will try:

<rule name="somerulename" patternSyntax="Wildcard" stopProcessing="true">

                   <match url="*" />

                   <conditions>

                       <add input="{HTTP_HOST}" pattern="^/company-reviews.aspx?i=(\d)/" />

                   </conditions>

                    <action type="Redirect" url="/(\d)/company-reviews.aspx{R:0}" />

               </rule>

I hope I have that right. Not sure why this is so confusing.

# March 21, 2011 12:30 PM

OWScott said:

Chekmate111,

If you're using URL Rewrite 2.0, the easiest way to tackle this is to use the "User-friendly URL" wizard when adding a new rule.

Enter your URL as yourdomain.com/company-reviews.aspx

Select the pattern you want, for example:

yourdomain.com/.../123

And check the 2 checkboxes, which handle incoming and outgoing rules to automatically address when the HTML uses the original URL format.

It should generate something like this:

<rewrite>

   <rules>

       <rule name="RedirectUserFriendlyURL1" stopProcessing="true">

           <match url="^company-reviews\.aspx$" />

           <conditions>

       <add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />

       <add input="{QUERY_STRING}" pattern="^i=([^=&amp;]+)$" />

           </conditions>

           <action type="Redirect" url="company-reviews/{C:1}" appendQueryString="false" />

       </rule>

       <rule name="RewriteUserFriendlyURL1" stopProcessing="true">

           <match url="^company-reviews/([^/]+)/?$" />

           <conditions>

               <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />

               <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />

           </conditions>

           <action type="Rewrite" url="company-reviews.aspx?i={R:1}" />

       </rule>

           </rules>

           <outboundRules>

       <rule name="OutboundRewriteUserFriendlyURL1" preCondition="ResponseIsHtml1">

           <match filterByTags="A, Form, Img" pattern="^(.*/)company-reviews\.aspx\?i=([^=&amp;]+)$" />

           <action type="Rewrite" value="{R:1}company-reviews/{R:2}/" />

       </rule>

       <preConditions>

           <preCondition name="ResponseIsHtml1">

               <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />

           </preCondition>

       </preConditions>

   </outboundRules>

</rewrite>

Here's a blog post on rewriting:

weblogs.asp.net/.../iis-url-rewrite-hosting-multiple-domains-under-one-site.aspx

And here's a link to all of my blog posts on URL Rewrite.  The last four are video blogs which you may find more helpful to get up to speed.

weblogs.asp.net/.../default.aspx

# March 21, 2011 1:37 PM

chekmate111 said:

Wow. I guess I don't understand....

I tried:

<conditions>

<add input="{HTTP_HOST}" pattern="/([0-9]+)/company-reviews.aspx" />

</conditions>

<action type="Rewrite" url="company-reviews.aspx?id={R:1}"/>

To see if I could rewrite the url, but nothing happens. Didn't I put in the right variables? The current url is: www.incorporatealabamabusiness.com/.../company-reviews.aspx

which should be rewritten to www.incorporatealabamabusiness.com/company-reviews.aspx

# March 21, 2011 1:47 PM

chekmate111 said:

Thank you so much! I am going to share this page on my facebook.

# March 21, 2011 2:00 PM

OWScott said:

Hi chekmate111,

The path part of the URL is {URL}, or you can use the top section (match url="").

The {HTTP_HOST} is the domain name part.  If you watch this quick video, it covers the parts of the URL: weblogs.asp.net/.../url-rewrite-servervariables-url-parts-http-to-https-redirect-week-9.aspx

So what you probably want is:

<conditions>

<add input="{URL}" pattern="^([0-9]+)/company-reviews/?$" />

</conditions>

<action type="Rewrite" url="company-reviews.aspx?id={C:1}"/>

Or, you can do this instead (they accomplish the same thing):

<match url="^(0-9]+)/company-reviews/?$" />

<action type="Rewrite" url="company-reviews.aspx?id={R:1}" />

# March 21, 2011 4:43 PM

Jace said:

I followed the steps and it works great with the exception of the querystring. It does not pass the querystring on redirect. The "Append query string" is checked. What am I doing wrong?

# June 9, 2011 1:38 PM

OWScott said:

Hi Jace, that should work simply by checking that checkbox.  I wonder if there is another rule that causes the querystring to drop.  To test, try moving your rule to the top and making sure that other rules aren't affecting your test.

# June 9, 2011 1:44 PM

Jace said:

Thank you for the response.

It's actually the only rule I have on there. I'm using PHP instead of .Net with IIS. Would that cause an issue?

# June 9, 2011 2:08 PM

OWScott said:

Hi Jace.  PHP wouldn't affect it.  I'm not sure why it wouldn't work.  Some things to check would be the IIS logs and Failed Request Tracing.  Both of them should confirm that the querystring was there for the first pass and maybe/hopefully give a clue on why it gets dropped the 2nd time around.

# June 9, 2011 6:01 PM

web design blog said:

Well I only had FTP and Plesk access. Through pleask it is a headache. Anyway I downloaded the web.config and used the wild-card method using a text editor.  It worked. Thank you very much. Nevertheless I'm still having problems getting wordpress to work in IIS.

# June 22, 2011 5:31 AM

OWScott said:

Hi Chris,

Good questions.  And thanks for the positive feedback.

Here's a quick tutorial video on how to understand the schema, which is a great way to find out all of the defaults:

dotnetslackers.com/.../Mastering-IIS-Understanding-the-Schema-Week-19.aspx

rewrite_schema.xml is the schema doc for URL Rewrite.

Regarding the poorly formed regular expressions: your first example is just more permissive.  For example, ^example.com$ will match exampleXcom too, but since it wouldn't exist in the real world in HTTP_HOST (unless you use host headers), it's not a problem to use either . or \. for the value.  I haven't tested performance for regex, but my guess is that \. is slightly faster because it's a literal match, but that’s just a guess.  The extra () around it is optional too.  They create sections which can be used in back references, but aren't needed if you don't use a back reference, or if you're matching everything.  I'm not aware of any performance differences one way or the other.  You're right that ^(.*)$ doesn't give you anything more than .* does except that it will offer one more back reference {R:1}, but since {R:1} will be the same as {R:0} it doesn't help any.  They both match everything.

As for appendQueryString, that one I don't know right off. I haven't experimented with it enough to know how it behaves.  My guess is the same as yours that it should append it when true, and not append it when false.  Do you have any other rules that are used instead?  Of course you could pull out the querystring in the redirect with a different rules, but that defeats the purpose of the appendQueryString attribute.

# July 5, 2011 11:55 AM

Chris Bowyer said:

Hi Scott,

Thanks for the heads up on the default settings. I have now added \Windows\System32\inetsrv\config\schema to my favourites for quick reference. Maybe someday, someone will create a cheat sheet. I do think the wizard could be improved though... i.e. deleting the defaults when changing e.g. ignoreCase="false" to ignoreCase="true". Mind you, although a bit programmatically clunky, it does help those not familiar with the defaults.

Also, thanks for the info on the poorly formed expressions. I have now finetuned a few things. Could you however, advise on {r:0} - is that a default back reference for when not enclosed in parentheses?

Still at stumps with the appendQueryString issue. Not that it is a major issue, but being an inquisitive type, I would love to eventually know what the go is.

# July 6, 2011 12:53 AM

OWScott said:

Hi Chris,

Yes, some of those settings are hard to handle perfectly in a UI.  For example, what do you do when you switch from a non-default value to a default value.  Do you delete the value or specifically set it.  UI's haven't been consistent over time on what to do in those situations.  Inheritance situations are even trickier (although fortunately not applicable in this case).

The {R:0} contains everything that *matched*. So this means that if you have a http_host of www.yourdomain.com and your regex value is "domain", then it will match, and {R:0} will be "domain" since that's all you searched for.  But, if you search for ".*domain.*" then it will catch the entire http_host and {R:0} will be "www.domain.com".  And, of course, "^domain$" won't even match, so {R:0} won't exist.

Check out week 10 and 11 from my series: dotnetslackers.com/.../LearnIIS7.  I cover most of this and more.

I'll do some testing on appendQueryString and see if I can repro what you're seeing.

# July 6, 2011 10:03 AM

OWScott said:

Hi Chris,

Regarding the appendQueryString, can you post your example of what doesn't work?  I just did a basic redirect with it set and without it and it does correctly honor that settings.  Although, I have heard other people say that it doesn't honor it too, so I don't doubt that it has an odd behavior in some situations.  

Also, make sure that you're not fighting with browser caching.  Try a fresh Chrome window in incognito mode to fight against caching.

# July 6, 2011 10:09 AM

Chris Bowyer said:

Hi Scott,

Thanks for the info on {R:0}. Very helpful!

I also checked out week 10 of your series. Very educational, but oops, week 11 is actually week 20

I also realised that I was thinking of the query string being page or directory/page. Anyway, I tested with an actual query string and voila, it worked as intended. Perhaps this is where others are going wrong too.

Just one other thing. Can you throw me any light on the <clear /> attribute?

# July 6, 2011 7:34 PM

OWScott said:

Hi Chris,

Thanks for mentioning about the wrong link.  I'll get that fixed.  In the meantime, here's the week 11 direct link: www.youtube.com/watch.

Great to hear that you've confirmed that the querystring attribute works correctly.  I'll keep that in mind when I hear of other similar issues.

The <clear /> element is used for collections.  Let's say that at the machine level you have a bunch of <handlers> set.  But at your site level you want to remove all references and start with your own choice of five (as an example).  The <clear /> removes all previous references for that section and allows you to start fresh.

In the case of URL Rewrite, if it's set at the site level, it removes all of the global rules ... although I don't believe it will help in that case since the global rules are applied before it processes the local <clear />.  I believe the <clear /> is just placed there as a standard practice to ensure that it's a clean start to avoid clashes of names.

# July 7, 2011 10:35 AM

OWScott said:

Thanks Chris, and you're welcome.

# July 7, 2011 5:47 PM

OWScott said:

Thanks ATaylor for the instructions.  This is a great reference for other people visiting this page.

Be sure to see my comments after Mark Howell's solution that give guidance on when to use a http redirect and when to use URL Rewrite.

One other thing to keep in mind with IIS7 and redirects is that they are delegated, so they are stored in the site's web.config file.  Therefore, it's essential that the new site points to a unique folder path.  It can't piggy back on the other site's site folder, otherwise the http redirect will end up getting applied to the other site too.

# July 18, 2011 10:11 AM

OWScott said:

Hi Tayyab,

There are a few tips that can help troubleshoot something like this.  Here are some:

- make sure you can manually browse to the non-www URL.  That ensures that it's not something unrelated to URL Rewrite

- when the redirect occurs it will hopefully show the URL in the address bar.  That will offer large clues on what it's doing wrong.

- Try in IE and Chrome (or other browsers) because they respond differently and may show more information in the address bar.

- Check the IIS logs to see what pages are being hit after the redirect

- Use Failed Request Tracing which will provide details on the rules, conditions and actions.

# August 24, 2011 8:58 AM

Rick Noelle said:

Thanks for taking the time to write this up Scott. Sometimes a straightforward example like this is exactly what you need to get headed down the right path!

# August 27, 2011 12:56 PM

OWScott said:

My pleasure Rick.  Glad to help out.

# August 27, 2011 1:33 PM

OWScott said:

Hi Tayyab,

Sorry for the delay.  In your example you have {HTTP_HOST}.  That's for the domain name.  What you probably need is to use {URL} instead, or you can enter it as match url="^Developer01/ABC"

That's why it's not getting caught, and throwing a 404.

# August 30, 2011 11:35 AM

Penny said:

IIS URL Rewrite doesn't work in shared configuration?

# October 17, 2011 2:07 PM

OWScott said:

Hi Penny,

Are you referring to my reply to Mark Howell?  That was referring to using multiple sites to handle the redirect, which is often not provided with a shared provider.

URL Rewrite itself works beautifully with the shared configuration, and also on a shared host, as long as they have URL Rewrite already installed.

# October 17, 2011 2:16 PM

Vikas said:

Can anybody please share the procedure to 301 redirect all the non-WWW versions of the URLs on a domain name to their WWW equivalent please?

I have currently been able to set up a 301 redirect from the non-WWW version of the home page to its WWW equivalent. However, if I visit the non-WWW version of the URLs on the site, they all respond with a 200 OK code. The WWW versions of the URLs respond with a 200 OK code too.

I want to 301 redirect all the non-WWW versions of the URLs to their WWW equivalent.

Kindly share the procedure if anybody knows how to accomplish this.

Thanks,

Vikas

# December 21, 2011 9:13 AM

OWScott said:

Hi Vikas,

Good question and sorry for the delay.  I just put up a blog post for you that explains how to do that.  You can find it here: weblogs.asp.net/.../redirecting-non-www-to-domain-equivalent.aspx

# January 5, 2012 10:01 AM

Argie said:

Hello,

I'm testing it, and I got the redirection only when I write contoso.com/Default.htm. But when I write just contoso.com I got the default IIS' welcome page.

I've checked the code on web.config and it's the same you wrote on this post (for wildcards).

Anyway, is it possible to use this method not just to add "www", but also (and at the same time) to change from "http" to "https"?

Thank you.

# April 5, 2012 9:21 AM

OWScott said:

Hi Argie,

I wonder if another rule could be running first that is set to stop processing further rules. Or, which site has the IIS welcome page?  Maybe another rule is catching and doing something with that.

As for doing the http to https at the same time, yes you can.  But do you want to direct all traffic to https or just for some pages like login and payment pages?  If you want to direct everything then in the redirect action at the bottom put https instead of http.

The problem though is that that doesn't handle pages that started out with http://www.contoso.com.  So, I would recommend that you have two separate rules for the www and the https logic since they don't parallel perfectly.

# April 5, 2012 9:51 PM

Argie said:

Thank you Scott. I was using just this rule for contoso.com.

At the end what I did was use this rule:

^www\.([.a-zA-Z0-9]+)$

that redirects to:

https://www.{HTTP_HOST}/{R:0}

And everything works fine now.

# April 10, 2012 4:20 AM

OWScott said:

Hi Argie, great, I'm pleased to hear that you have a working rule.  Thanks for confirming.

# April 17, 2012 11:24 AM

James said:

That was a very good walkthrough.  Exactly what I needed.

# June 20, 2012 9:27 AM

Refael said:

Great Post !!!

Help me a lot :)

Lot of thanks

# July 1, 2012 12:03 PM

OWScott said:

Hi Argie,

The first rule looks good to me. My only guess is that your domain name has a - in it, which wouldn't be caught by that rule. For the condition, how about using:

<add input="{HTTP_HOST}" pattern="^www\.(.+)$" negate="true" />

That will make sure to get everything that doesn't start with www.

# September 26, 2012 11:15 AM

Argie said:

Thanks Scott. My domain doesn't has an "-" in it, but I gonna change this rule as you advise me.

I really don't know what to do, because I was using this rule for some months without problems, and then I realized that it stopped to work.

Do you have another way to get the same result? I.e., perhaps you know how to add "www" to "non-www" domains with a different rule...

Thank you!

# September 27, 2012 5:44 AM

OWScott said:

Hi Argie,

Your rule still looks good to me. If you haven't recently, I suggest checking at the server level (and site level) and confirming that there aren't other rules.

Also, Failed Request Tracing (FRT) is a good way to log what is happening and find out which conditions match or fail. If you setup a trace for status codes 200-999, enable it, and then refresh your page using http://mydomain.com then open the generated log file in IE and search for your rules to see what is happening.

# September 27, 2012 11:38 AM

OWScott said:

Hi Argie,

Can you send me your trace file?  Use the contact link up at the top of this page. You can just paste the entire body of the trace file when you tested with http://mydomain.com.

# September 28, 2012 4:56 PM

Argie said:

Scott, the problem is that any trace file is generated.

I don't know why...

# October 1, 2012 4:14 AM

OWScott said:

Do you mean that 'no' trace file is generated? If that's the case, double check at the site level that you turned on failed request tracing. You can find it from the Actions pane. It's a different step than creating the rule.

# October 1, 2012 12:28 PM

Argie said:

Hi again Scott,

regarding to this problem with the rule to add "www" to the url of my site, I wasn't able to fix it, yet.

One of the test I did was to delete that rule an create a "canonical domain name rule". This didn't works.

But by checking the IIS, I realized that I have a "Default web site" that shows two folders, corresponding to the two real physical folders I have inside "inetpub/wwwroot". This default web site hasn't rules, and it is stopped.

I also have defined another website, which is the real website I'm using (where the rules are applied), and where I can see a folder and an application defined into it. Both they are refering to the same two physical folders defined on the "default web site" (i.e., by "refering" I mean they have the same name that the two folders inside "default web site". Because, of course, are the same physical folders).

Well, I told you all this just for to ask you if you believe that I should delete this "default web site", because this could be the cause that the "no-www" rule doesn't work.

I don't know, this is just a theory :)

Thank you.

# October 5, 2012 5:36 AM

OWScott said:

Hi Argie,

That's helpful. Good troubleshooting. Your steps are correct for failed request tracing so since it didn't show anything then another site must be catching the request. And that lines up with your follow-up comment.

I bet the issue isn't related to URL Rewrite but it's related to the site bindings. Take a look at your site bindings and make sure that the http and https bindings for www and non-www bind to the correct site. And also make sure that another site isn't catching the binding by being more specific.

And yes, if you have a site that isn't really needed that is pointing to the same folder, then you might as well delete it so that it won't get in the way.

# October 6, 2012 12:04 AM

Argie said:

Well, I deleted the "default web site". Then I changed the binding of another (stopped) website that was using the same https bind than the site that has problem with no-www rule. Now on this stopped site the port 80 is pointing to www.contoso.com, and it hasn't a 443 port defined there.

So, the website with problems on the rule has defined ports 80 and 443, and it is using the right domain (that it isn't, of course, www.contoso.com). But the problem persist.

I don't know what else I can do...

# October 9, 2012 9:57 AM

OWScott said:

Hi Argie,

Why don't you use the contact form at the top of this page and let me know your phone number and a good time to call. I'll give a you a holler and we can see if we can get this figured.

Scott

# October 9, 2012 11:06 AM

Argie said:

Thank you very much Scott for the help you gave me yesterday with this problem!

As you told me, the solution was to add one more binding pointing to "domain.com" (without www). Because without this binding the rule doesn't works.

Argie

# October 11, 2012 3:54 AM

OWScott said:

You're welcome Argie. I'm pleased to hear that it's working now. Thanks for the update.

# October 11, 2012 12:20 PM

OWScott said:

Hi Nikunj,

There are two ways to do this. One is to create two rules. One rule should check for HTTPS = on and the other for HTTPS = off.  Then in the action send to either http or https, depending on the rule.

Another option is to add this condition to your rule: <add input="{CACHE_URL}" pattern="^(.+)://" /> That will create a back-reference to the http or https.

Are you getting a certificate warning too? That will occur if you visit https://domain.com but your certificate is for www.domain.com. That's a chicken before the egg issue since the IIS binding occurs before URL rewrite can redirect. There isn't a good solution except to get a cert for domain.com. However, it's often not an issue because it's only a problem if someone visits that path directly from a link, and if you don't post any links anywhere to https://domain.coom then it shouldn't impact anyone.

# October 26, 2012 6:05 PM

Dave Whelan said:

Hi Scott,

I have been asked to setup a redirect using the following.

Basically, all requests to non-existent resources must be redirected to index.php?sef_rewrite=1 plus any original query parameters.

Any pointers please.

# November 29, 2012 7:12 AM

OWScott said:

Hi Dave,

Give this rule a try. It should achieve that.  After you're done testing, remove the redirectType="Temporary" to make it a permanent redirect.

<rule name="sef_rewrite redirect" stopProcessing="true">

 <match url=".*" />

 <conditions>

   <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />

   <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />

   <add input="{CACHE_URL}" pattern="^(.+)://" />

 </conditions>

 <action type="Redirect" url="{C:1}://{HTTP_HOST}/index.php?sef_rewrite=1&amp;{QUERY_STRING}" appendQueryString="false" redirectType="Temporary" />

</rule>

Make sure that index.php exists or you'll get a redirect loop.  

# November 29, 2012 8:30 AM

OWScott said:

Hi Mohiuddin,

I would do that with two different rules. The first rule will catch all traffic to http://mydomain.com/anything and add the www. It sounds like you have that part.

Then create another rule that handles the index.html. It should look something like this:

<rule name="Redirect index.html" stopProcessing="true">

 <match url="^index\.html" />

 <action type="Redirect" url="http://www.mydomain.com" />

</rule>

# March 6, 2013 9:39 AM

elmer said:

I'd follow you're instruction but after that my webpage has an error of Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.

How can I resolved this?? I'm using codeigniter

# May 16, 2013 6:21 AM

OWScott said:

Hi elmer,

You'll get too many redirects if there is a loop. This can occur if your condition includes the URL in the action. For example, let's say that in the action you're going to www.domain.com, but in the condition you're checking for (www\.)?domain\.com, that will cause a loop.

Another easy way to get a loop is if another component fights with you. For example, if you add the www with URL Rewrite, but your site (or CMS) removes the www. That can cause a redirect loop.

# May 16, 2013 3:18 PM

sunil said:

How handle request for https

If request comes like https://domain.com

it will rediect to http://domain.com

so did we need to put this rule twice for http or https

If any one have solution pls give us

www.saraswatipgcollege.com

# June 7, 2013 9:46 AM

OWScott said:

Hi Dave and elmer. I just noticed your questions now so I must have missed them. I'm sure you've long since resolved them, but if not please ask again and I'll reply.

# June 10, 2013 11:27 AM

OWScott said:

Hi sunil,

Here are two blog posts that cover that topic with details on how to tweak for your situation:

http://tinyurl.com/nmavbq5

http://tinyurl.com/4lj4v5g

# June 10, 2013 11:28 AM

Adam Senour said:

I didn't even know this was possible in web.config until yesterday and I was doing it using server-side code before.

Thanks, Scott.  This is much more logical.

# July 23, 2013 10:59 AM

Curtis D. said:

How would I rewrite or redirect with HTTP_ headers that are already set and append that as query parameters in the URL?

# September 20, 2013 6:33 PM

OWScott said:

Hi Curtis,

You could do something like this:

<rule name="Add headers to querystring">

   <match url=".*" />

   <conditions trackAllCaptures="true">

       <add input="{HTTP_SOMETHING}" pattern="(.+)" />

   </conditions>

   <action type="Rewrite" url="{R:0}?http_something={C:1}" appendQueryString="true" />

</rule>

That will watch for a HTTP header called "Something" and append to the querystring. This is a rewrite so it happens in the background without changing the URL in the browser.

# September 24, 2013 11:37 AM

Alok Kumar Thakur said:

Hi OWScott,

In one of my application I have set url redirection using the step you have mentioned above and it is working great.

But for one of my folde in my application url came as follows

mydomain.com/webservices/services.aspx?methodname=methodname

so above url get redirected to www.mydomain.com/webservices/services without having query string.

Here if you can help me either way

1. How to set 301 redirection with query string

or

2. how to exclude one folder or page from 301 redirection.

If you need further explanation then please let me know.

For now I am using following rule in web.config

<rewrite>

  <rules>

   <rule name="Redirect domainname.com to www" patternSyntax="Wildcard" stopProcessing="true">

    <match url="*" />

    <conditions>

     <add input="{HTTP_HOST}" pattern="domainname.com" />

    </conditions>

    <action type="Redirect" url="http://www.domainname.com/{R:0}" />

   </rule>

  </rules>

 </rewrite>

now requirement is if request from domainname.com/webservices/service.aspx?methodname=mymethod.. then it should preserve the query string or its fine not to redirect to www in this case.

Your help will be highly appreciated..

# November 13, 2013 8:33 AM

OWScott said:

Hi Alok,

Sorry for the delay.

That rule that you have should include the query string. It will do that by default. You can add it manually with {QUERY_STRING} but it's not needed.

Could there be something else that your web server is doing to remove that? For example, another rule, or a load balancer, or something else?

# November 19, 2013 7:31 PM

Rehan said:

Hi Friend, can anyone help me to redirect my website!

here is the problem.. when i try to redirect my

qatar.example-company.com/index.html to www.qatar.example-company.com/ in my cpanel

(IIS Administration Console, i get this error message in browser.. (This webpage has a redirect loop).

Please help me..

Thanks

Rehan

# November 26, 2013 12:52 AM

OWScott said:

Hi Rehan,

If you happen to see this still, a redirect loop is probably from the condition being too permissive so that it matches the same domain name in the action.

# January 13, 2014 10:58 PM

Shawn McConnell said:

I'd follow you're instruction but after that my webpage has an error of Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.

How can I resolved this?? I'm using codeigniter

# March 17, 2014 8:37 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)