Scott Forsyth's Blog

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

.

  • Scott Forsyth

Hosting Needs

Training and Dev Labs

IIS URL Rewrite – Hosting multiple domains under one site

In a shared hosting environment, it’s a common desire to have a single IIS website that handles multiple sites with different domain names.  This saves the cost of setting up additional sites with the hoster. 

At ORCS Web, we’ve supported this situation for many years using ISAPI Rewrite.  Now, with URL Rewrite for IIS 7, it’s easier and it’s integrated right into web.config.  In this blog post I’ll set out to cover the essentials for hosting multiple domain names under a single account using URL Rewrite.

This post assumes that you are using URL Rewrite 1.0, 1.1 or 2.0.  I’ll follow-up in a later post on more advanced ways to take this further yet, using the new features of URL Rewrite 2.0.

Part II will cover the outgoing rules available in URL Rewrite 2.0 to take this a step further.

First, the file structure

Let’s lay out the directory structure for this example.  Assume that you have 3 domain names.  They are: masterdomain.com, site2.com and hawaiivisit.site2.com.  You’ve created your directory structure like this:

image

Let’s assume that masterdomain.com was already in the root of the site and can’t easily be moved.  However, site2.com and hawaiivisit.site.com need to be set up.  Each of these folders have a website within them.

Directing the domain name to the server

First, make sure that when you browse to the website by domain name, that it resolves to the correct IP address.  This is handled at the DNS level.  Your DNS entry for site2.com and hawaiivisit.site2.com will often be identical to masterdomain.com and are managed through your DNS provider.

Catching the site when on the server

If you host with a web hosting company then they will take care of this.  If you host yourself, make sure to set a site binding so that the expected site processes the domain name.  If you use host headers, be sure to add the extra bindings for them.

Redirecting the site to a subfolder

Now that you have the domain name directed to the server and site, URL Rewrite comes in to direct it to a subfolder.

First, make sure that your web host supports URL Rewrite on the server that you’re hosted on.  The following assumes that it’s installed and supported.

You can use IIS 7 Manager which gives a friendly interface for creating rules.  If you prefer to write them directly in web.config, I’ll include the rules below.

First, open up URL Rewrite:

image

I’ve come to prefer RegEx rules instead of wildcard rules.  I find that wildcard rules reach their limit pretty quickly.  Regular expressions can be daunting at first but it’s pretty easy to pick up the basics.  Here’s an excellent reference to get started: http://www.regular-expressions.info/reference.html

To create the rule click on “Add Rules…”.

image

Select the “Blank Rule” template and click OK.

For the name, enter your domain name, or whatever makes the most sense to you.

Match URL section

In the Match URL Section, leave the defaults to match the pattern and Regular Expressions.  For the pattern, enter (.*) without the parentheses.  The “URL” is the part after the domain name.  i.e. www.ThisIsTheDomain.com/ThisIsTheURL.  It’s the domain that we’re interested in now, not the URL.

Conditions

The Conditions section is where we’ll do most of the work.  Expand that section if it’s collapsed and click “Add”. 

The domain name is contained within the HTTP header called {HTTP_HOST}.  Here’s where the fun comes.  The regular expression pattern that will match www.site2.com or site2.com (without the www) looks like this: ^(www.)?site2.com$. 

Here’s what that means. 

  • The ^ is the character that signifies the start of the string.  That ensures that something.www.site2.com doesn’t also get included with this rule.
  • The $ is the character that marks the end of the string.
  • ( ) parentheses are used to create section groups. 
  • ? means that something is optional.
  • Therefore, (www.)? means that with www. or without, either are accepted.

After filling in these fields you should have something like the following:

image

Now, here’s the part that many people wouldn’t guess at first.  Since URL Rewrite works on the URL only, while most code (ASP.NET, ASP, PHP, etc) works at the server level, they aren’t aware of each other.  Just because you rewrite the URL doesn’t mean that the code has any clue of the change.  As a result, any time that ASP.NET automatically creates the path, it will likely clash with the URL Rewrite rule.  For example, Response.Redirect(“~/”) will redirect to the root of the application.  That means that it can create a path like www.site2.com/site2.  Notice the extra site2 in the path.  The login page for ASP.NET will mess with you too.

A future blog post will cover how to hide the /site2 using URL Rewrite 2.0, but the easy solution is to ensure that www.site2.com and www.site2.com/site2 both go to the same place.  Both should be served from …\masterdomain.com\site2.  It means that the URL can be longer than you may prefer, but it allows the site to continue to function.

To achieve this, add an exclusion condition so that this rule doesn’t redirect at all if the URL starts with /site2/.

There are 2 ways to achieve this.  You could go back to the URL section where we previously entered .* and update that section.  There isn’t anything wrong with that at all.  For no particular reason that I can think of right now, I prefer to do this from the conditions section.  Here’s how to do it:

Add another condition where the condition input is {PATH_INFO}, and set the dropdown to “Does Not Match the Pattern”, and set the Pattern to ^/site2/.  That means that the PATH_INFO must start with /site2/.  Note that you shouldn’t end with the $ this time because you want sub-sub folders to work too.  It should look like this:

image

Action Section

We’re nearly done.  In the Action section, first set the “Action Type” to Rewrite.  Then set the Rewrite URL to \site2\{R:0} and ensure that the “Append query string” checkbox is checked.  The {R:0} is a back reference to the URL.  It will allow the URL to be carried through dynamically in the request.  The Append query string ensures that the query string itself will carry through.

The complete rule should look like this:

image

That’s it.  Save and test.

Using a Text Editor

You may prefer to use a text editor or to see the config directly.  The rule generated for web.config looks like this:

<rewrite>
    <rules>
        <rule name="site2.com" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^(www.)?site2.com" />
                <add input="{PATH_INFO}" pattern="^/site2/" negate="true" />
            </conditions>
            <action type="Rewrite" url="\site2\{R:0}" />
        </rule>
    </rules>
</rewrite>

And, the rule for hawaiivisit.site2.com is similar.  It looks like this:

<rewrite>
    <rules>
        <rule name="hawaiivisit.site2.com" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^hawaiivisit.site2.com$" />
                <add input="{PATH_INFO}" pattern="^/hawaiivisit/" negate="true" />
            </conditions>
            <action type="Rewrite" url="\hawaiivisit\{R:0}" />
        </rule>
    </rules>
</rewrite>

The other things

I wanted to briefly mention what isn’t covered in this blog post that you may want to consider. 

  • DNS. The ‘how to’ for your domain name purchase and directing isn’t covered here.
  • Statistics. If you use  a client-side option like Google Analytics then this will work just as well under a single account.  However, if you are using a log based statistics program like SmarterStats then it’s up to you to set rules in SmarterStats to filter out or sub-divide the statistics into useful sections i.e. 1 per site.
  • Email. You will likely need to setup another mail account with your host, or add the new domain as a domain alias to your existing account.
  • ASP.NET inheritance. web.config inherits down the entire path but the ASP.NET folders do not inherit past application boundaries.  More on that here.  One workaround if ASP.NET inheritance fights with you is to not have a site in the website root.  Instead, place all sites in their own subfolder.
  • You’ll likely need to mark the folder as an application so that it is an ASP.NET application.  (assuming ASP.NET of course)

Happy URL Rewriting!

Posted: Jan 26 2010, 08:40 PM by OWScott | with 79 comment(s) |
Filed under: , , ,

Comments

IIS URL Rewrite ??? Hosting multiple domains under one site - Scott … Abbey by about said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site - Scott &#8230; Abbey by about

# January 27, 2010 1:26 AM

IIS URL Rewrite ??? Hosting multiple domains under one site - Scott … New just to Me said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site - Scott &#8230; New just to Me

# January 27, 2010 3:42 AM

IIS URL Rewrite ??? Hosting multiple domains under one site - Scott … Hair just to Me said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site - Scott &#8230; Hair just to Me

# January 27, 2010 5:46 AM

IIS URL Rewrite ??? Hosting multiple domains under one site - Scott … Audio by about said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site - Scott &#8230; Audio by about

# January 27, 2010 5:57 AM

IIS URL Rewrite ??? Hosting multiple domains under one site - Scott … Domain on Me said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site - Scott &#8230; Domain on Me

# January 27, 2010 6:38 AM

IIS URL Rewrite ??? Hosting multiple domains under one site - Scott … | Webmasters feeds said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site - Scott &#8230; | Webmasters feeds

# January 27, 2010 7:40 AM

John said:

This article was very helpful.

You have my thanks for writing it

# January 27, 2010 10:45 AM

IIS URL Rewrite ??? Hosting multiple domains under one site - Scott … Airline by about said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site - Scott &#8230; Airline by about

# January 27, 2010 2:31 PM

Twitter Trackbacks for IIS URL Rewrite ??? Hosting multiple domains under one site - Scott Forsyth's Blog [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 IIS URL Rewrite ??? Hosting multiple domains under one site - Scott Forsyth's Blog         [asp.net]        on Topsy.com

# January 27, 2010 7:00 PM

IIS URL Rewrite ??? Hosting multiple domains under one site - Scott … Affiliate by about said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site - Scott &#8230; Affiliate by about

# January 28, 2010 10:26 AM

IIS URL Rewrite ??? Hosting multiple domains under one site – Scott … | VRYTEK said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site &#8211; Scott &#8230; | VRYTEK

# February 3, 2010 11:48 AM

IIS URL Rewrite ??? Hosting multiple domains under one site | 007Nova Articles said:

Pingback from  IIS URL Rewrite ??? Hosting multiple domains under one site | 007Nova Articles

# February 4, 2010 3:58 PM

Harriet said:

Thanks so much - my MS hosting service recently migrated to IIS 7 and most of my redirects broke. No one at the hosting service could give me an explanation, but this is it! My site is in a folder and the folder name gets appended twice because of the rewrite rule. Thanks for giving me my sanity back!

# February 8, 2010 9:39 AM

Harriet said:

Could you help just a bit more? How can I incorporate the exclusion in an httpd.ini file? Here is my current code. It needs to exclude urls that already start with site1, as you describe in the article.

[ISAPI_Rewrite]

### subdomain redirect ###

RewriteCond Host: (?:.+\.)?mydomainname\.com

RewriteRule (.*) /site1/$1 [I,L]

# February 8, 2010 9:42 AM

OWScott said:

Hi Harriet.  Pleased to hear about the help with IIS7.

For ISAPI rewrite, you can add the exclusion like so:

[ISAPI_Rewrite]

### subdomain redirect ###

RewriteCond Host: (?:.+\.)?mydomainname\.com

RewriteRule (?!/site1)(.*) /site1/$1 [I,L]

That means "optionally not" /site1 in the path in the RewriteRule.

# February 8, 2010 10:35 AM

Harriet said:

That is exactly what I needed - amazing that no one at the hosting company had a clue how to do this. After they migrated they just slapped the httpd.ini files into everyone's root without considering the fact that it would break lots of redirects. I was just about in tears last night!

I would love to make a paypal donation to you for your help. If you contact me here: http://colormybans.com/ticket/ with a paypal address, only I will see it. Or point me to a donation button if you have one.

Thanks again for your help - Harriet

# February 8, 2010 10:56 AM

OWScott said:

Great, glad you got it working!  It sounds like an odd configuration with your hosting company if they are placing you in subfolders rather than with your own site.

Your comments are thanks enough for me!  But, I'll contact you just to get in touch.

# February 8, 2010 11:24 AM

loebpaul said:

Hello,

I am having a problem with IIS 7 and rewrite. I have rewrite set up for one of my domains, but the rule is being applied to all of my domains on my VPS. Can you please help!?

Thanks

Paul

# February 10, 2010 6:27 PM

OWScott said:

Paul, you can add a condition that causes the rule to only apply to one domain.  Use the server variable {HTTP_HOST} and if you're using Regular Expressions, set the value to

^(www.)?yourdomain.com$

That will catch the www and non-www for yourdomain.com, but it won't catch for any other domains on your server, or on the site.  (your rules can be created at the global level or site level, so if you only have 1 domain on a site, you can simply create the rule at the site level and it will achieve the same result)

# February 10, 2010 8:08 PM

Exim Bank ??? Tanzania, streamlines HR processes with Adrenalin … | Business Ethics Wisdom said:

Pingback from  Exim Bank ??? Tanzania, streamlines HR processes with Adrenalin &#8230; | Business Ethics Wisdom

# February 11, 2010 9:14 AM

Jessie said:

Hi,

I want to create subdomain rewrite from the following url:

www.domain.com/MyPage.aspx

to

myname.domain.com/Testing

So, I create a new rules using blank rule,

<rule name="TestPage" enabled="true" stopProcessing="true">

                   <match url="(.*)" />

                   <conditions logicalGrouping="MatchAll">

                       <add input="{HTTP_HOST}" pattern="^([A-Za-z0-9_]+)\.domain\.com/Testing/" />

                   </conditions>

                   <action type="Rewrite" url="MyPage.aspx?url={C:1}" />

               </rule>

When i browse the page (myname.domain.com/Testing), i can't go to the exact page which is (www.domain.com/MyPage.aspx) .

Is my rule or pattern correct? Can anyone give me some guidelines or examples what I should add in my rules? (e.g: Pattern in Match URL, Conditions & Action).? Thanks.

# February 28, 2010 9:26 PM

OWScott said:

Hi Jessie,

Try this out:

<rule name="TestPage">

 <match url="^testing(/$|$)" />

 <conditions>

   <add input="{HTTP_HOST}" pattern="^([A-Za-z0-9_]+)\.domain\.com$" />

 </conditions>

 <action type="Rewrite" url="/MyPage.aspx?url={C:1}" />

</rule>

{HTTP_HOST} has the domain name exactly, without the URL.  So it can't have /Testing in it.  Put that in the match url instead.  Everything else looks good.

Note that my example for the url is exactly "testing" or "testing/".  If you want it to be more flexible, for example testing/anything, then remove the (/$|$) at the end.

# March 2, 2010 10:13 AM

Andrew said:

Going back to Harriet's issue:

Herriet, you're using ISAPI_Rewrite v2, even though there's v3 available(that allowes you to use httpd.conf and .htaccess instead of http.ini), but Helicon Ape may provide help that's hard to overvalue for your work.

# March 5, 2010 3:40 AM

links for 2010-06-02 | The Gryphin Experience said:

Pingback from  links for 2010-06-02 | The Gryphin Experience

# June 2, 2010 4:02 PM

URL Rewrite ??? Multiple domains under one site. Part II - Scott Forsyth's Blog said:

Pingback from  URL Rewrite ??? Multiple domains under one site. Part II - Scott Forsyth&#39;s Blog

# August 3, 2010 5:08 PM

Running more domains (sites) on 1 hosting account. | Dizid said:

Pingback from  Running more domains (sites) on 1 hosting account. | Dizid

# August 10, 2010 3:57 PM

Tom said:

Thanks for the post, it definitely helped me.

One issue, your code has "^(www.)?site2.com", but you say it should be "^(www.)?site2.com$" with a "$". Mine only worked without the "$".

# January 8, 2011 5:04 PM

OWScott said:

Thanks Tom. Not sure why yours would fail without the $.  Using regular expression mode, the $ signifies the end of the compare string.  That means that with or without the $ should be fine since no other domain names end with com{something}.  Glad you got a working solution in any case.

# January 8, 2011 5:30 PM

noahcoad said:

This has been super handy!  Very well written instructions.  Thanks for covering the {HTTP_HOST} exception.  That part was left out of other posts I've seen and made the difference in getting BlogEngine.NET to run on my discountasp.net hosting account under a 2nd domain name.

# January 24, 2011 12:45 PM

bestservers said:

Its great to know  Hosting multiple domains under one site.Anyway, Thanks for sharing.

# February 8, 2011 2:30 AM

GeoffreyG said:

Scott,

You ROCK, this has been very helpful to me! I was able to create a web.config file and get the rewrite to work for the top level, but I'm still have problems.  For example, when I put in the domain:

www.mySecondaryDomain.com

It will be directed to:

www.myPrimaryDomain.com/folder1

However, my problem is that stuff under the "folder1" root cannot be found by the "mySecondaryDomain.com" addresses now.  For example, if I try to go to:

www.mySecondaryDomain.com/test/1.html

I get a 404 error and am NOT taken to the file at:

www.myPrimaryDomain.com/folder1/test/1.html

Does this make sense? Essentially, I want to replace the "myPrimaryDomain.com/folder1" with "mySecondaryDomain.com" and have it work for all links and pages. Any help you can further offer here (beyond the massive amount of useful info you've already provided) would be greatly appreciated!

Thanks,

GeoffreyG

# February 9, 2011 3:09 AM

OWScott said:

Hi GeoffreyG.  What you described is what the rule is supposed to do.  The {R:0} is a back reference to the URL after the domain name, and it should retain it on the rewrite.

Some options for troubleshooting are:

Test locally on the server to get a detailed error message, or temporarily set your errors to detailed.  The 404 error should tell you what location it attempts to use.

Use Failed Request Tracing (FRT) if you have access to the server, or ask your host or administrator to help capture a FRT log.  This will tell you which URL Rewrite rules, if any, are catching.

You can temporarily try a 'break test'.  Edit your rule to sent a custom error, like 500.0.  If you get a 500 error then the rule worked.  If you don't, then the rule didn't catch.  This will help you narrow down whether the error is related to the URL and conditions or the action.

# February 9, 2011 10:30 AM

GeoffreyG said:

Hi Scott,

Thank you SOOOO MUCH! I've now figured out the problem here and I might not have got it without all your help.  Actually, the problem ended up being another Rewrite rule that was conflicting (sorry, I'm still learning here), and I didn't realize it until after your message because the conflicting rule was in the Web.Config the "folder1" dir and while your rule resides in the Web.Config in the site root dir!  Anyway, thanks again, I really appreciate all your help and this wonderful article - keep up the AWESOME work!

Thanks again,

GeoffreyG  

# February 9, 2011 9:03 PM

OWScott said:

Hi GeoffreyG.

Great!  I'm pleased to hear that you were able to troubleshoot that to resolution.  IIS 7's distributed config is certainly nice, but it can be easy to miss conflicting rules.

# February 9, 2011 9:47 PM

stefan said:

hi,

i'm not good at iis but have to solve this:

http://www.mysite.de/

should be redierectet to

http://www.mysite.de/subfolder/subfolder/subitem.aspx

with this solution its not working... only if i redirect to:

www.mysite2.de/.../subitem.aspx

it works fine... what to do?

ps: i cant use the texteditor for that rules... where may i find it? iis7 ...

thanks a lot ... stefan

# February 16, 2011 1:40 PM

OWScott said:

Hi Stefan,

As long as URL Rewrite is installed, the editor is available in IIS Manager at the site or global level.  It's under the "Url Rewrite" icon.

Probably the best way to work through this is to post your existing rule in the iis.net forums at forums.iis.net/1152.aspx.  There's great support over there in an interactive forum (I reply occasionally there too).

# February 17, 2011 9:14 AM

aay said:

How can I write regular expression that replacelocalhost/.../invoke ? name="abc"

to

localhost/.../invoke

any help will be nicethanks

# March 9, 2011 11:30 PM

Ian said:

Can I add rewrite rules to a sub domain using this method?

my parent directory has rules for rewriting .html to .php

when I add a sub folder for site 2 in the root, how can I use the same rules under site?

thanks

<rule name="*.php" stopProcessing="true">

                   <match url="^(.*).html$" ignoreCase="false" />

                   <action type="Rewrite" url="{R:1}.php" />

               </rule>

# March 10, 2011 7:51 AM

Ian said:

Solved,

I had to create a new web.config in the site2 directory at wwwroot/site2/web.config

# March 10, 2011 7:56 AM

OWScott said:

Hi Ian.  Great!  Glad you got that solved.  Thanks for the update.

# March 11, 2011 9:23 AM

OWScott said:

Hi aay,

Do you want to keep it hidden but still have it available?  If so, that's difficult and would need to be done in code by replacing it with session information or POST data.

If you simply why to strip the querystring, you can create a rule with .* for the URL and the redirect rule can be http://{HTTP_HOST}/{URL}, and then don't check the include querystring checkbox.

Or, you can create a condition to filter to just some querystrings like "^name=&quot;abc&quot;$", or "^name=" to get anything that starts with name=.

# March 11, 2011 9:26 AM

gichan said:

Great. This is the exact fact i was finding for years. Can anyone guess the reason? I will give a small clue. It is Windows 7 and IIS. You guys think the rest.

Anyway thanks a lot and wish you good luck...

# May 27, 2011 7:18 AM

gichan said:

url rewrite has always been great. But i never thought this much deep.

# May 27, 2011 7:21 AM

ozjohnson said:

Hi Scott,

Have just installed MS Rewrite to a newly delegated version of our website installed to www.carnet.com.au/carnet and need to resolve to www.carnet.com.au

(currently the root domain displays the IIS home page)

Going by your config edit example, do I have the correct structure with the following:

<rewrite>    <rules>        <rule name="carnet.com.au" stopProcessing="true">            <match url=".*" />            <conditions>                <add input="{HTTP_HOST}" pattern="^(www.)?carnet.com.au" />                <add input="{PATH_INFO}" pattern="^/CarNet/" negate="true" />            </conditions>            <action type="Rewrite" url="\CarNet\{R:0}" />        </rule>    </rules></rewrite>

Regards,

Mark J

# July 13, 2011 2:32 AM

OWScott said:

Hi Mark.  That looks good to me.  Does it work for you?

Also, if you only have one site on your server, you can just update the root folder for the site and point it directly to the CarNet folder.  You don't even need to use URL Rewrite.  URL Rewrite can help with multiple domains on a single site, but it's generally only necessary if you are on a shared host or you have some other reason why you can't create another site.

# July 13, 2011 10:53 AM

ozjohnson said:

Hi Scott,

Thank you for the prompt response.

No, unfortunately and I am flumoxed.

My developers have ended up just redirecting the page and I hate that.It has messed with a bunch of hard coded urls in various places...And there will be at least one, maybe two other sites.

I forawarded your sample syntax and my interpretation, as copied above and they tell me it didn't work.

So when you say "just update the root folder for the site and point it directly to the CarNet folder." do you mean redirect?

Mark J

# July 14, 2011 10:23 AM

OWScott said:

Hi Mark,

Each situation is different so I'll speak generally, but if you explain your situation further I can be more specific.

If you manage your own server and it's not on a shared infrastructure then you can rely on multiple sites and host headers instead.  

The solution in this blog post is most useful in a shared hosting situation where you only have 1 website but you want to host multiple domain names with multiple sites.

If you haven't seen in it yet, check out my video series: dotnetslackers.com/.../LearnIIS7.  Week 5 talks about the different IIS bindings.  That would be the better solution if you have access to the whole server.

# July 14, 2011 10:47 AM

ozjohnson said:

Thank you.

We have dedicated "enterprie" VM servers running windows server 2008.

I'll check your article, thanks again for responding

# July 14, 2011 10:58 AM

OWScott said:

Sounds like dedicated sites may be the way to go then.

# July 14, 2011 11:09 AM

Ross said:

Hi Scott,

This is the only article that even comes close to explaining how to host multiple sites in one account, and I carefully created the rule based on your instructions but it's not working for me.

I downloaded web.config after creating the rule in IIS Manager, here it is (I masked the actual domain for privacy reasons);

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

<match url=".*" />

<conditions>

<add input="{HTTP_HOST}" pattern="^(www.)?newdomain.org$" />

<add input="{PATH_INFO}" pattern="^/newsite/" negate="true" />

</conditions>

<action type="Rewrite" url="\newsite\{R.0}" />

</rule>

Do you see anything wrong?

Also note that I first created a domain pointer for the new domain (inside my hosting hosting account), and I hope the DNS for the new domain is not causing the problem. It resolves to the same IP as the main site.

Thanks, Ross.

# August 8, 2011 12:02 AM

DanielM said:

Hi, Scott

Thanks for the very informative post.  I think I'm almost there, but I'm running into an issue.  I have multiple domain names pointing to the same site (not a subdirectory of the site.  i.e. my site bindings have several domain names).  I just want to take requests to one of the domain names (lets call it site1.com) and redirect it to site1.com/home.aspx.  This way, I can display a different home page when site1.com is entered, but the rest of the site is still intact (i.e. no published links break and site2.com and site3.com still resolve to the normal default.aspx.  I tried to adapt the instructions above and in the comments, but still, whenever I go to site1.com, I see the standard default.aspx page rather than my redirect to home.aspx.  Any ideas?

Thanks, Daniel

# August 11, 2011 10:57 AM

DanielM said:

probably should have included this from my web.config:

<rule name="site1.com redirect" stopProcessing="true">

  <match url=".*" />

  <conditions>

    <add input="{HTTP_HOST}"

       pattern="^(www.)?site1.com$." />

  </conditions>

  <action type="Redirect"

       url="site1.com/home.html" />

</rule>

# August 11, 2011 11:05 AM

OWScott said:

Hi Ross,

Your example looks good to me except that the {R.0} should be {R:0}.  Everything else looks like it should work.

You can escape your .'s in the {HTTP_HOST} line to make them "^(www\.)?newdomain\.org$" but that wouldn't have prevented them from working.

The {R.0} would have prevented it from working so that could very well be the only issue.

# August 20, 2011 12:37 PM

OWScott said:

Hi DanielM,

You have a . at the end of your "^(www.)?site1.com$.".  That will cause an issue.  Also, if you're doing a redirect, add a http:// to the beginning of the url value.

However, you're going to run into a loop with that rule because it will keep redirecting.  What you can do is set the match url to <match url="^$" /> which means that it will only process the rule if it's exactly nothing.

Alternately you can use a rewrite instead of a redirect.  The rule should be something like this (untested)

<rule name="site1.com rewrite" stopProcessing="true">

 <match url="^$" />

  <conditions>

    <add input="{HTTP_HOST}"

      pattern="^(www\.)?site1\.com$" />

 </conditions>

 <action type="Rewrite"

      url="/home.html" />

</rule>

# August 20, 2011 12:43 PM

DanielM said:

It would still be cool to know how/if this can be done, but I had to figure it out ASAP, so I used the Page_Load on the standard Default.aspx.  It may not be pretty, but I'm self-taught...  here is what it looks like:  

protected void Page_Load(object sender, EventArgs e)

  {

      if (!IsPostBack)

      {

          string requestedURL = Request.ServerVariables["HTTP_HOST"];

          if (requestedURL == "www.site1.com" || requestedURL == "site1.com")

          {

              Response.Redirect("www.site1.com/home.html");

          }

      }

  }

# August 20, 2011 12:50 PM

OWScott said:

Hi DanielM,

Sorry for the delay while on vacation ... and I approved your posts out of order so that makes it a bit confusing.  

However, thanks for the follow-up reply.  That looks like a good workaround.

# August 20, 2011 1:03 PM

rtyecript said:

I really liked the article, and the very cool blog

# August 22, 2011 5:09 AM

David Berry said:

Really nice post!  This has helped me a bunch! :)

# August 26, 2011 12:38 AM

tummurugoti said:

Thanks for the excellent blog.

I have two websites pointing to same Application in IIS. The difference is my www.site1.com points to http://IP/Website and www.site2.com points to http://IP/Website/Home as this is an MVC application.

When I do the url routing on second site my URL is changing to www.site2.com/home. I don't want to show the '/home' at the end. How would I do this?

# September 16, 2011 12:35 AM

OWScott said:

tummurugoti, the problem is that URL Rewrite and ASP.NET/MVC live at different levels.  The route mappings in MVC aren't aware of the URL Rewrite rules.

What you may need to do is setup 2 route mappings per URL.  One is for Html.RouteLink, and another is for the incoming request.  For example:

routes.MapRoute("HomeLink", "", new { controller = "Home", action = "Index" } );

routes.MapRoute("HomeIncoming", "site2", new { controller = "Home", action = "Index" } );

Then setup a 2nd URL like in the article above that rewrites (not redirects) to /site2/.

Then you would reference the link with @Html.RouteLink("Home", "HomeLink").  That will generate the reference to just / in the HTML, but when the request comes back in it will know to tag on something unique that you can watch for in your MVC routes.

# September 16, 2011 11:20 AM

Adam said:

Hi, I've spent all weekend searching for solutions to this problem and I've found nothing.  The standard (.*) does not solve this problem.

I want to create a rule for TWO separate subdomains for my website.

I want two subdomain sites to redirect to an https URL.

http://subdomain.mydomain.com

subdomain.mydomain.com

These should BOTH redirect to https://subdomain.mydomain.com

Here's the tricky part.

I also have this website:

admin.subdomain.mydomain.com

admin.subdomain.mydomain.com

This needs to redirect to

admin.subdomain.mydomain.com

The problem with using the standard (.*) is that if you try to go to the admin site you get redirected to the regular site, so I need a separate regex rule for each site.

Can anyone help me? This is a very urgent problem and I've pretty much exhausted my options! Thanks in advnace!  

# September 20, 2011 9:31 PM

OWScott said:

Hi Adam,

What you can do is use [^\.]* to represent any character except for dot [.].  

So, to get a 3rd level domain but not a 4th level domain, you can use this regex expression: ^[^\.]*\.mydomain\.com$

# September 21, 2011 9:38 AM

Krunal said:

Hi, my requirements are:

host normal site if someone access it using www.domain.com

and I also want to host it on different domain, like, www.otherdomain.com, this will actually load domain.com/other/ from application.

but when someone access it using otherdomain.com, it will be masked like otherdomain.com.

So when someone access it like www.otherdomain.com/page-name, then it will actually load, wwww.domain.com/other/page-name but original domain name will be masked off.

How to configure it ?

# October 3, 2011 7:01 AM

OWScott said:

Hi Krunal,

What you described is exactly what this article covers.  It accomplishes all of your requirements.  If you go through the post above, it shows the step by step instructions on how to achieve this.  

If you've completed the steps and it still doesn't work, let me know which part doesn't work and I'll try to help.

# October 4, 2011 1:10 PM

markos said:

you are the best!

# October 11, 2011 8:42 PM

Jaypalsinh said:

Hy all Can you tell me how to rewrite page .

when i type url : www.blahblah.domain.com

then redirect my page to another page ...

Please Help me to Do this...

Thanks & Regard

Jaypalsinh Parmar.

# October 24, 2011 1:46 AM

OWScott said:

Hi Jaypalsinh,

You can do that with a rule like this:

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

  <match url=".*" />

  <conditions>

    <add input="{HTTP_HOST}" pattern="^(www\.)?blahblah\.domain\.com$" />

  </conditions>

  <action type="Redirect" url="http://newdomain.domain.com/{URL}" />

</rule>

For more details, check out my video series which covers URL Rewrite: dotnetslackers.com/.../LearnIIS7.  Weeks 9-14 are focused on URL Rewrite.

# October 24, 2011 9:15 AM

newyearnt said:

<rewrite>

 <rules>

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

     <match url=".*" />

     <conditions logicalGrouping="MatchAll">

       <add input="{HTTP_HOST}" pattern="^([a-zA-Z0-9]+).subdomain.mydomain.com$" />

     </conditions>

     <action type="Rewrite" url="/Default.aspx?Name={C:1}" />

   </rule>

 </rules>

</rewrite>

It's not work. Please explain for me.

# October 26, 2011 6:10 AM

OWScott said:

Hi newyearnt, what issue do you have?

Basically that rule will take something.subdomain.mydomain.com and write *all requests* to /Default.aspx?Name=Something.

So that means that something.subdomain.mydomain.com/aboutus.aspx will also be served up by /Default.aspx?Name=something.

If that's your intention, the rule looks good.

# October 27, 2011 9:06 AM

Jaypalsinh said:

Hy I want to rewrite url in asp.net like usename.domain.com to home.aspx so how can i do this

Please Help me to do this is it posible on local host ...

please tell me...as soon as posible

Thanks

Jaypalsinh Parmar

# November 2, 2011 5:37 AM

Jaypalsinh said:

Hy OWScott . i had try on local host but it;s not working so please tell me what i have to do. in the name of use shuld be dynamic.

Please let me know how it can be posible

my page is localhost or my PCname/bgtard/

if i type in url like abc.pcname/bgtard/ then it shoud be redirect on pcname/bgtard/mainpage.aspx

AND STILL URL SHOULD DISPLAY SAME NAME abc.pcname/bgtard/

IS IT POSSIBLE

# November 2, 2011 6:01 AM

Jaypalsinh said:

It's still not working

when i try

http://jay.127.0.0.1/bgtard it gives me error webpage not found.

<rewrite>

 <rewriteMaps>

<rewriteMap name="DynamicRewrite">

</rewriteMap>

</rewriteMaps>

<rules>

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

<match url="(.*)" />

<conditions logicalGrouping="MatchAll">

<add input="{HTTP_HOST}" pattern="^(www\.)?([a-zA-Z0-9]+)\.127\.0\.0\.1/bgtard$" />

</conditions>

<action type="Redirect" url="http://www.google.com" redirectType="Temporary" />

               </rule>

           </rules>

       </rewrite>

this is my redirect code please help me to do like

jay.127.0.0.1/bgtard then it redirect to homepage.aspx and url shoulde be  jay.127.0.0.1/bgtard

# November 2, 2011 7:13 AM

OWScott said:

Hi Jaypalsinh,

The trick is with the domain name.  127.0.0.1 is an IP address so it can't be mixed with a domain name format like jay.127.0.0.1.

What you can do is add an entry to your hosts file for testing.  That's in c:\windows\system32\drivers\etc\hosts.

Create jay.localhost for testing.  Or just jay.testdomain.int, or whatever you want.  The IP should be 127.0.0.1.  That will give you a nice domain name to test with.

Once you add the hosts entry, then make sure that it calls up *something* on your site.  It doesn't matter yet if it's the right thing.  As long as it calls up something then you know that the domain name points to your server and IIS handles it.

Then start working on your URL Rewrite rules.

# November 4, 2011 10:40 AM

Antti said:

Hello,

I hope you still read these comments. Anyway this is a great article! I managed to do rewrite just as described but my problem is that I have css and some user controls that point to the root folder and those don´t appear after rewriting the url to subfolder.

# January 26, 2012 3:36 AM

OWScott said:

Hi Antti,

Yep, I still read the comments. :) What you can do is make sure that the condition section is set to "match all".  Then create conditions for each file or file or pattern that you *don't* want to redirect for.  For example, where {URL} not equal to ".+\.css" will mean that the rule won't rewrite for anything.css.

# January 26, 2012 9:52 AM

ukon_myst said:

help please. I'm sure i've missed something in this article and all the comments. It is a very good article, but I am making mistakes somewhere. Here is my plan: i have multiple sites on iis 7. For one site, i will need to rewrite the urls. for instance. www.ukon_myst.com/subdir1/subdir2/subdir3/subdir4/page.aspx must become infrared.ukon_myst.com/subdir1/subdir2/subdir3/subdir4/page.aspx. Basically all i need rewritten and to remain the same for the User NOT the server is the very first subdomain. I do have dns entries, and host headers for the subdomain that needs to be rewritten. I seem to be losing it on the rules. please help! here is the rule as it stands now, I know it is wrong.

(ps.i could have 100s of these rewrites)

<rewrite>

           <rules>

               <rule name="infrared.subdomain.com" stopProcessing="true">

                   <match url=".*" />

                   <conditions>

                       <add input="{HTTP_HOST}" pattern="^infrared?.subdomain.com$" />

                   </conditions>

                   <action type="Redirect" url="infrared.subdomain.com/.../default.aspx" />

               </rule>

           </rules>

       </rewrite>

# February 1, 2012 9:47 AM

ukon_myst said:

in addition, if the user uses the url http://infrared.ukon_myst.com then it should rewrite/redirect to http://infrared.ukon_myst.com/subdir1/subdir2/subdir3/subdir4/page.aspx

thanks!

# February 1, 2012 9:57 AM

OWScott said:

Hi ukon_myst,

It sounds like you could use two rules.  One for the redirect and one for the rewrite.  You will need something unique so that you can tell which situations to redirect and which not to.  In my example below I used a start of subdir1/subdir2/subdir3/subdir4 but you could use something more general.

This will redirect from www.subdomain.com (or just subdomain.com) to infrared.subdomain.com (you can pull subdomain.com dynamically with {C:2} if you want).

Then after it does a client-side redirect for the users' sake, you can do a rewrite so that someone hitting the default page will actally be hitting the default page for your infrared site.

<rule name="infrared.subdomain.com - www to infrared" stopProcessing="true">

   <match url="^subdir1/subdir2/subdir3/subdir4" />

   <conditions>

       <add input="{HTTP_HOST}" pattern="^(www\.)?(subdomain\.com)$" />

   </conditions>

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

</rule>

<rule name="infrared.subdomain.com ensure subfolder">

   <match url="^$" />

   <conditions>

   <add input="{HTTP_HOST}" pattern="^infrared\.subdomain\.com$" />

   </conditions>

   <action type="Rewrite" url="/subdir/subdir2/subdir3/subdir4/page.aspx" />

</rule>

# February 1, 2012 10:21 AM

ukon_myst said:

Ok, thank you I will try to work it out! Again, a great blog. Thank you!

# February 1, 2012 2:01 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)