Scott Forsyth's Blog

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

Cloud Resources

IIS Resources

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!

Comments

John said:

This article was very helpful.

You have my thanks for writing it

# January 27, 2010 10:45 AM

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

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

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

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

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

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

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

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

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

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

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 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

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

Amyth said:

Hey Scott,

Thanks for this post. It has been useful in reducing a major change in our application however we're currently experiencing problems with RedirectToAction methods all across our MVC 3 site.

Basically, we've got a web application set up on IIS 7.5 which has got a web.config file, a folder called "1" and some other folders. We are using your technique of re-writing to forward all requests to the website to a web application that is in 1 folder. so when someone requests: www.domain.com it actually runs the application. However, we are noticing that when the actions have got RedirectToAction it is trying to request www.domain.com/1/controller/action. An example is: when the user tries to login, we call RedirectToAction("Index", "Admin") after authentication. However, the actual thing doesn't work. I am hoping that this is a re-write/routing issue (fingers-crossed)

# February 14, 2012 8:16 AM

OWScott said:

Hi Amyth,

That does sound like the difference between URL Rewrite and MVC.  MVC isn't really aware of URL Rewrite since it's rewritten before it reaches the MVC part (for the most part anyway).

It's a bit of a pain to setup but you can setup outgoing rules to catch the /1/ and rewrite them to /.  Here's a post on that: weblogs.asp.net/.../url-rewrite-multiple-domains-under-one-site-part-ii.aspx

Alternately you can use a RedirectToRoute and setup specific routes, although I haven't tested to confirm that it will bypass the /1/ too.

Any paths created by the server need to either be specifically handled on the server or rewritten on the way out.

# February 14, 2012 9:21 AM

Amyth said:

Thanks for that Scott.

I have since noticed that the problem isn't with the MVC routes. I wanted to check if the server side code for domain.com/account/login is being run to I added some logging there. I have noticed that the request doesn't reach there at all.

I used fiddler to generate a post to that url with appropriate headers and can see that the desired result is achieved. However, when posting from the browser, the server-side post action for logon just doesn't get called!

Any ideas why?

P.S. Thanks again for taking the time to reply.

# February 14, 2012 9:42 AM

OWScott said:

Hi Amyth,

It sounds like two things then.  You're right that using my rule example above it will support /1/{route} even if it doesn't look as pretty.  So the login issue must be a different issue.

Does domain.com/1/account/login work?  Does it work if you disable the rule?  I would start by pulling URL Rewrite out of the picture and making sure that your login works.  If it does, then we can focus on the rules.  Otherwise at least you know that URL Rewrite isn't the cause.

# February 14, 2012 10:31 AM

Amyth said:

I think the re-write is fine. We've been able to make login work by changing the following:

From:

Html.BeginForm("LogOn", "Account", FormMethod.Post)

To

Html.BeginForm()

I would love to know what the difference is. I now am fairly confident that the re-write wasn't causing any problems. The word in the team is that the routing was at fault. We've got so many custom routes that nobody knows what is happening.

I wish I could tell you what went wrong and how we resolved it. After our release we are going to investigate it further!

P.S. Following you on twitter, will let you know.

# February 15, 2012 6:03 AM

OWScott said:

Hi Amyth,

Sounds like you're narrowing it down.  That's the key thing.  

Here's the overload for your first BeginForm:

msdn.microsoft.com/.../dd460344.aspx

The action and controller specified must be different than what is calculated from the action that you're in.

Here's a good blog on route debugging: haacked.com/.../url-routing-debugger.aspx

All the best in your troubleshooting.  I'm curious to hear what you figure.

# February 15, 2012 9:19 AM

Vaibhav said:

Hi,

Please let me know how it will work on iis6.

# February 23, 2012 8:09 AM

Rey Mambo said:

HTML.BeginForm() works,

I wanted to know why it doesn't work when you put attributes on it say a 'name' or 'id'.

Btw the application is located inside a subdirectory

# February 23, 2012 12:39 PM

OWScott said:

Hi Vaibhav,

It's the back reference to the domain that would cause the issue.  If you use IIS Manager and then edit the condition and run the test app, you can see what the back references will be.  There are a couple other little things to tweak too.

In your example, that's for something.abc.com which is different than your first example above.  You can set the {HTTP_HOST} condition to "^(www\.)?(.*)\.(mydomain\.com)$"  That will get something.mydomain.com and also allow an optional www at the beginning.

For abc.mydomain.com you can use {C:2} to get "abc" or {C:3} to get "mydomain.com".

# February 25, 2012 3:23 PM

OWScott said:

Hi Rey,

It's not overly straight forward to add the Id.  The way to do it is to use the httpAttributes. The problem is that there isn't an overload that just takes the httpAttributes so you'll need a longer overload.  Here's an example (see the approved answer). forums.asp.net/.../1361569.aspx The "foo" "bar" are for your controller and action.

# February 25, 2012 3:27 PM

OWScott said:

@Vaibhav.  This won't work in IIS6.  The best option for IIS 6 is ISAPI Rewrite.

# February 25, 2012 3:48 PM

Ahmed said:

Hi

Am not familiar with URL Rewrites att all and wonder if you just can point me in the right direction.

i have a domain where the student can access thier sites by writing

www.domainname.com/username

the website is under thier home folder in a folder thats called Public

so the path to the home folder will be

path\username\Public

the root of IIS is pointing into the path. so all i would like to have help with is a rewirte rule that just adds public to each request.

Regards

# March 1, 2012 6:31 AM

OWScott said:

Hi Ahmed,

That's a fun one.  The trick is that you need to split the first part of the folder from the rest.  You probably also want to exclude some files or folders.  I believe that the following will do the trick

<rule name="Run from public subfolder" enabled="true">

   <match url="^([^/]+)(.*)$" />

   <action type="Rewrite" url="{R:1}\public\{R:2}" />

   <conditions>

       <add input="{URL}" pattern="^/(scripts|includes)" negate="true" />

       <add input="{URL}" pattern="^[^\\]+\." negate="true" />

   </conditions>

</rule>

Here's what it means:

"^([^/]+)(.*)$" -> at least one character and all characters until the first slash.  That will be added to the {R:1} back reference.  The slash and on will be in {R:2}

"^/(scripts|includes)". -> Don't run this rule if the folder starts with scripts or includes.  You can add more folders to this list.

"^[^\\]+\." -> if a dot comes before a slash then we assume that it's a file in the root folder, so don't run the rule on that.

# March 2, 2012 4:28 PM

nazo said:

Hi, is this better then ASP.NET URL Routing? and what if the hosting server doesn't have this IIS URL Rewrite installed can I still use it in my app by configuring in web.config and include the .dll?

thanks

# March 3, 2012 10:43 AM

OWScott said:

Hi nazo.  ASP.NET URL rewriting is a great solution for the developer.  It's more common for SEO friendly URLs and especially with MVC applications to create the URLs.  It works for the current application and doesn't generally cross application boundaries.

URL Rewrite is good for global settings on a domain like redirecting to www or hosting a site from a subfolder.  It's also a good solution for after-the-fact type situations where the admin or developer wants to handle some URLs.  It also has a good rewrite mapping solution if you move a site from an old location to a new location.

It really depends on which you are comfortable with.

URL Rewrite is a server level application that needs to be installed.  It's not an xcopyable solution.

# March 3, 2012 2:50 PM

Craig said:

Hi

I have a hosted site which I've created 3 subdomains as follows:

mysite.com (root)

 admin.mysite.com (sub domain)

 public.mysite.com (sub domain)

 resources.mysite.com (sub domain)

   \images (sub folder)

If a user browsers to mysite.com, the content is served up from public.mysite.com, the browser URL will show mysite.com.

What I want to do is share image and css files in the resources sub domain.  So say my default.aspx in public.mysite.com refernces images from resources.mysite.com.  I'm unclear how to make the URL to an image in public.mysite.com\default.aspx appears as mysite.com\images\myimage.jpeg

Essentially I want to share the resources subdomain between the other sub domains.

If you have any ideas, I'd greatly appreciate it

# March 5, 2012 6:04 AM

OWScott said:

Hi Craig,

You can do that with conditions in the rules.  For example, in your public.mysite.com rewrite rule you can add a condition where {PATH_INFO} is not "^/images/".  That will prevent the rule from running for images and will leave it in the mysite.com\images folder.  If you want it to run from mysite.com/resources.mysite.com/images then just create a rule that appears before your public.mysite.com rule that watches for {PATH_INFO} = "^/images/" and rewrites to the path that you want.  

Hope that makes sense.  Let me know if you would like for me to put together an example.

# March 6, 2012 11:22 AM

John said:

Hello Scott

I think my setup matches the original post criteria for the most part.

I have a domain, abc.com.  This is the root of the site.  I then got a second domain, xyz.com, and set up a domain pointer for it to go to abc.com

I want to map xyz.com into a subfolder, essentially  abc.com/xyzcom

I then installed an application, say myapp into a subfolder of that,  abc.com/xyzcom/myapp/

So if I enter xyz.com/myapp/ in my browser, I do see myapp (Thanks for that)

But, if I type xyz.com/myapp (note trailing slash is gone), my browser URL winds up being xyz.com/xyzcom/myapp  It does show myapp correctly still, but has the xyzcom folder visible in the URL. Any thoughts on how to correct for this?

Thanks!

# March 15, 2012 11:36 PM

OWScott said:

@John,

The issue is that your app (likely ASP.NET) doesn't realize that it's in a sub-folder so all of the code generated links and redirects will add the full path.

Part II addresses that exact situation.  I can't say that it's the easiest rule, but it should do the trick: weblogs.asp.net/.../url-rewrite-multiple-domains-under-one-site-part-ii.aspx

# March 19, 2012 1:19 PM

Santhosh said:

Thanks so much Scott for sharing this...It helped me a LOT...

# March 30, 2012 8:04 AM

OWScott said:

Hi Timmy,

The {HTTP_HOST} variable is just the domain name, so you'll need to make the http/https decision with {HTTPS}=on/off instead.

The http/https part is the tricky part, especially if you're going to use a MatchAny condition to support multiple domain names.  There are some tricks to be able to do this but none which are very easy.  Can you say that since it's a redirect than people are probably arriving from a search engine and you don't mind always pushing them to http?  If so, just create a single rule for http.  If you have another rule later in the list then it can redirect them back to https again on the secure pages.

If that is fine, then I believe the rule that you're looking for is:

{HTTP_HOST} = ^(subdomain)\.(domain\.com)$

The {C:1} = subdomain, {C:2} = domain.com

So you can set your action url = "http://{C:1}2.{C:2}/{R:0}"

That will redirect to subdomain2.domain.com.

# May 11, 2012 10:25 AM

VizMan said:

Hi Scott,

I'm trying to create a mobile version of my web site using a subdomain like mobi.mysite.com

i'd like to set it up with the following:

- map the subdomain to a subfolder called 'mobi'

- preserve the subdomain url

- not have to set it up subdomain as another webapplication

- allow files in subfolder to access dll in bin dir for main site

- have all this on shared hosting (arvixe)

Possible?

Thanks in advance

# May 16, 2012 2:21 AM

OWScott said:

Hi VJ,

One thing right off is the last character of the HTTP_HOST conditions.  It should be a $ rather than a *. Since you mentioned that it worked for the redirect I assume that's just a typo when you wrote the summary though, but check that to confirm just in case.

A Rewrite should be a path on disk rather than a web URL, so that may be all that it's missing.  Probably just /sites/{C:1}/{R:1} should do the trick.

Thanks,

Scott

# June 12, 2012 1:36 PM

VJ said:

Thanks Scott for your quick reply. The wildcard * just works fine with the redirect as does the $. But in both the cases only the redirect works and not the rewrite.

Since I'm configuring this for SharePoint, unfortunately the disk paths can't be pointed at as the pages are unghosted.

I thought that the rewrite can be applied at the subdomain levels aswell. May be its just that SharePoint does not allow it :(

Thanks for your time!!

Cheers,

VJ

# June 13, 2012 7:47 AM

OWScott said:

Hi VJ,

You're right about the *.  That means that the m in com could be repeated, so mydomain.comm could also be the value of {R:0} if you had a domain name like that.  In other words, it's not hurting or helping.  It won't come up in a real-world situation.

What you're talking about is proxying.  That's possibly and the URL Rewrite rule is pretty much the same. You will need to install Application Request Routing and enable proxying at the server level.  You can find ARR on www.iis.net and search for ARR.  After you do that, a good way to start is to create a rule using the URL Rewrite wizard (proxy rule) at the site level. It will ask if you want to enable the proxying.

I believe that will do the trick although I know that SharePoint can mess with the URLs and I'm unsure how much, but you're heading down the right path.

# June 13, 2012 4:57 PM

goldarrow said:

Hello Scott,

First off.   Great blog and videos, thanks for taking the time to create them!

I followed your example, and it worked great.   But I have run into a snag.  The relative paths to images, css,… are not working.  How is the best way to deal with this?  Outbound rule?  

Thanks in advance for your help

# July 11, 2012 5:50 PM

OWScott said:

@goldarrow.  Sorry for the delay as I was traveling.

Is the HTML itself wrong, or are the images themselves not working?

For example, if you manually enter the relative URL does it work in the browser?  

In the example above it's important for some links to have the following condition:

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

Make sure that the path is correct.  By having that it will work for URLs like /images/blank.gif and /site2/images/blank.gif.  

So an outbound rule usually isn't needed for dependencies like that.

Hope that helps point you in the right direction.  Feel free to explain further with examples and I'll try to help further.

# July 16, 2012 6:47 PM

OWScott said:

@goldarrow.  

Probably the easiest solution is to update the virtual studio web server (Cassini or IIS Express) to be in the root of the site.  It shouldn't be localhost:port/projectname, but rather it should be localhost:port/.  You can edit that in the properties of the site.

The other option is to make sure that all of your images are relative to the page they called from, so rather than /images/img.png you may need images/img.png or ../images/img.png depending on the relation of the page to the images.

I don't believe that this URL Rewrite rule is impacting this though.  I bet if you tested without the rule that it would have had a problem too.  This URL Rewrite rule will still leave everything with the same relation to each other ... oh, unless you previously had /projectname/images/img.png for the path which would have worked in dev and in the site if the root folder was /projectname.  

In any case, it should be resolvable by reviewing the relative paths, or else updating the visual studio web server to be in the root of the site.

# July 20, 2012 7:18 PM

OWScott said:

Hi Parminder,

There are two ways to do this.  One is to change the references in your HTML to use the fully qualified domain name (FQDN).  So use something like //cms.mysite.com/images/image1.png.

That's often the best bet and it doesn't involve anything fancy.  It just means that you need to update the source code.

The other option is to use a reverse proxy like ARR+URL Rewrite and to take incoming requests to www.mysite.com/images and in the back end make a request to cms.mysite.com/images.  I think that the first option will do the trick for you.  If not, let me know more about the project and I'll see what I can recommend.

# August 21, 2012 5:39 PM

JPineda said:

Hi Scott, thanks for this great post.

I'm not sure if I can solve my problem with URL-rewrite or how I should do this and I'm hoping that you can help me.

Here's my problem:

We recently bought 3 domain names as "redirects" to our main domain (maindomain.com) which we host (IIS 7).  Under maindomain.com we have a virtual directory where we want people to go when they hit any of the 3 domain names. For example:  maindomain.com/virtual/home.aspx.  When people type newdomain1.com, newdomain2.com or newdomain3.com I want to redirect to maindomain.com/virtual/home.aspx.

When we registered newdomain1.com, newdomain2.com and newdomain3.com, we set them to redirect to maindomain.com at the registrar level.  This was done since the registrar does not allow to redirect to a specific page but to a domain (maindomain.com).

I was under the impression that I could figure this out in IIS 7 so that when traffic came through maindomain.com from newdomain1, 2 or 3.com I could "grab" it and redirect it to maindomain.com/virtual/home.aspx.  But I have been unable to make this work.

The problem is that we want do to this without having a separate public IP for newdomain1, 2 or 3.com

Can you please help me?  I have tried different things in IIS but nothing works.  I tried creating a website for newdomain1.com that basically redirected to maindomain.com/virtual/home.aspx but that did not work as I believe that it is not being hit because when newdomain1.com is typed in a browser, the registrar is taking over and redirects it to maindomain.com.

I then tried using URL-rewrite/redirect following your directions here on the maindomain.com website in IIS, but the rule doesn't see newdomain1.com as coming in since, again, the registrar is sending traffic to maindomain.com.

Can you please let me know if what I'm trying to do is even possible?

Your help is greatly appreciated!

# October 11, 2012 4:42 PM

OWScott said:

Hi JPineda,

From your description it sounds like the register is doing a full redirect, and it's occurring before it reaches your server. Therefore, you can't make a URL Rewrite decision because URL Rewrite gets it too late in the process.

The solution is to update the DNS record at your register so that it is set the same as maindomain.com. Basically you want a Host record for newdomain1.com (and the the other domains) which points to the same IP address as maindomain.com. And you'll need an Alias for www.newdomain1.com which points to newdomain1.com. And turn off the redirect at your registrar.

Then the domain will arrive at your server as 'newdomain1.com' and you can make routing decisions based on the HTTP_HOST (domain name).

# October 12, 2012 10:19 AM

Blayne said:

Great Article.  Thank you!

I got this to work great using directories and multiple domain names - using your blog.

However, I am now trying to do this with an Application (instead of a directory).  The application is an MVC3 app.  Works great navigating to "my.domain.com/app".  But when I put the rewrite rule in and navigate to "my.domain.com" I get a 403 Access denied error.

I have logged the rewritten URL and it is identical to the url that works: "my.domain.com/app".

Have you came across this issue before?

Thanks,

Blayne

# December 19, 2012 1:28 PM

OWScott said:

Hi Blayne,

That should work, especially if my.domain.com/app works.

A 403 could be caused from no default document, but that's not really applicable with an MVC app.

Possibly the app folder isn't marked as an application. Your description sounds like it is, but it's best to confirm just in case you're starting with a fresh site or something.

Also, try a test.htm page at my.domain.com/app/test.htm and my.domain.com/test.htm and see if that works.  That will help rule out (or confirm) clashes with MVC's URL rewriting.

# December 19, 2012 3:39 PM

Challenged said:

So, I have PHP website and .NET website running on IIS 7.5.

Each has it's own domain name, IP, SSL Cert.

The reason I am using to justify for management/client is this is the only and best way to do this.

Am I correct?

(oh please say yes and/or explain)

Your fan,

John A. Davis

# March 5, 2013 2:57 PM

OWScott said:

Hi John,

I don't know enough information to answer for sure. Each situation can be different and sometimes the business requirements dictates the technology and sometimes the technology nudges the business decisions in a certain way.

I assume that both sites are related, but that you've split them into two technologies because of different requirements. For example, you have new developers who prefer .NET or PHP, or you've inherited a 3rd party app.

.NET and PHP generally play well together, although you may have some inheritance issues with .NET. So it may be possible to have both in the same site, but you may find it easier to keep them as unconnected sites.

The answer is that it depends. Can you explain your reason to separate them?

# March 5, 2013 3:15 PM

Challenged said:

No reason to separate them except one is in PHP and one will be build in .NET. I've got both languages running on new IIS 7.5 Windows 2008 R2, but I was almost sure I couldn't have the .php and .aspx pages all running from the same website.

# March 5, 2013 3:49 PM

Challenged said:

And I just want to say, wow, thanks for reading your comments this long after your blog date. All of us are grateful.

# March 5, 2013 3:50 PM

OWScott said:

Hi John,

I'm pleased to be able to reply and have a discussion like this.

IIS gives a lot of flexibility. You are able to have both in the same site since the file extension determines which framework to use. There can be some minor challenges but overall it is possible if you want to go that way.

Separating them into different sites can have benefits too, particularly allowing separate dev teams or environment so that they don't step on each other. It really comes down to your preference. IIS/PHP/.NET will support you either way.

# March 5, 2013 8:34 PM

Challenged said:

I hadn't thought of the development teams angle. Which is a reality with our 2 languages.

The main problem is the SSL certificates which require domain names associated.

yourwater.oregon.gov

and

dwp.oregon.gov

The client might not want the second one that is being used for SSL cert and .NET website. But I am having serious doubts about URL Rewrite with only one domain name/SSL cert.

In other words, would a redirect still maintain the "https" status of redirected website if there was only one SSL cert and it was associated with the PHP website?

Someone types www.yourwater.oregon.gov URL and goes to the PHP website default page.

they then type www.yourwater.oregon.gov/otherWebsite/ and are redirected to the .NET website default page.

Since this is a different website, would it or could it still share the SSL cert?

I know IIS is very capable. But I need to get past that to resolving a pretty much unknown configuration on a new server where business happens 7/24.

# March 6, 2013 12:56 PM

OWScott said:

Hi John,

As far as the cert is concerned the root site or the /otherWebsite/ site appear the same. The cert can't tell the difference and it doesn't know which language is used. So in that regard it should work well.

There will be minor things, like all of your absolute paths for the /otherWebsite need to become relative paths, or they need to start paths with /otherWebsite. But those are minor things that are usually easy to fix.

The cert itself just needs to be installed on the server and www.yourwater.oregon.gov and www.yourwater.oregon.govotherWebsite will both work without any cert warnings or other issues.

# March 6, 2013 6:54 PM

Challenged said:

Oops. I can't believe I made the mistake.

The 2nd website in .NET is "dwp.oregon.gov".

2 websites, one PHP, one .NET.

2 SSL certs 1 bound to "yourwater.oregon.gov"

and 1 bound to "dwp.oregon.gov"

Will redirect from "yourwater.oregon.gov/whateverFolder/" to

"dwp.oregon.gov" still maintain https status?

# March 7, 2013 2:24 PM

OWScott said:

Got ya. That part depends on your redirect. If you use URL Rewrite then you can maintain the protocol in the redirect: weblogs.asp.net/.../url-rewrite-protocol-http-https-in-the-action.aspx

# March 7, 2013 5:37 PM

wgprop said:

I am having issues configuring iis url rewrites.  

When i do a Response.Redirect("~/Account/RegisterExternalLogin.aspx");

i get file not found can't find file

/FolderName/FolderName/Account/RegisterExternalLogin.aspx

The FolderName get added twice to the path.

I need the path to be:

FolderName/Account/RegisterExternalLogin.aspx

my iis configuring:

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

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

                   <conditions>

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

                       <add input="{PATH_INFO}" pattern="^/mydomain.com/" negate="true" />

                   </conditions>

                   <action type="Rewrite" url="\mydomain\{R:0}" />

               </rule>

<outboundRules>

               <rule name="mydomain-outbound rule" preCondition=".aspx pages only">

                   <match filterByTags="A, Area, Base, Form, Head, Link, Script" pattern="^(?:mydomain|(.*//[_a-zA-Z0-9-\.]*)?/mydomain)(.*)" />

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

               </rule>

               <preConditions>

                   <preCondition name="bb1">

                       <add input="{SCRIPT_NAME}" pattern="\.aspx$" />

                   </preCondition>

                   <preCondition name=".aspx pages only">

                       <add input="{SCRIPT_NAME}" pattern="\.aspx$" />

                   </preCondition>

               </preConditions>

           </outboundRules>

thanks for your help!

# March 17, 2013 7:32 PM

OWScott said:

wgprop,

In your example you used /mydomain. Does that correspond to FolderName?

The issue is that ~\ is the ASP.NET path and not the IIS front end path. However, there was an update (IIRC it was .NET 3.5 SP1) that offered support so that the ~\ path was aware of URL Rewrite. So I would assume that what you want would work without any customization. However I can't tell for sure how your rule maps to the folder structure.  

I have two suggestions. First, make sure that you have the latest .NET hotfixes applied. That may address it.  Otherwise, try using relative paths rather than the ~\ and that will work (it's just not as portable).

# March 20, 2013 12:14 PM

wgprop said:

I got rid of the ~\ in the path, and that did not fix the problem, I have the same problem as before.  The mydomain in the rewrite is referring to the folder name, unfortunately the rewrite, or something writes the folder name twice, which causes the page not to be found.  I thought by adding the outbound rule I could fix this, but I haven't been successful

# March 22, 2013 12:49 PM

OWScott said:

Hi wgprop,

You can do that with an outbound rule (although doing it from code is easier if you can). The thing is that it's a redirect that it sent to the client and not a full page, so you need to catch the redirect in the response location.  Outgoing Rule #2 in this blog post covers that: weblogs.asp.net/.../url-rewrite-multiple-domains-under-one-site-part-ii.aspx

Actually your example looks like it may have been based on this.

What I would do for testing is to make the regex rule really straight forward. For example:

<rule name="response_location URL">

   <match serverVariable="RESPONSE_LOCATION" pattern="^yourdomain.com/.../>

   <action type="Rewrite" value="yourdomain.com/.../RegisterExternalLogin.aspx" />

</rule>

Then start to build up the regex after you have that confirmed.

Your favorite tool for this should be Fiddler. It's great at seeing the header and what you need to rewrite.

# March 26, 2013 3:38 PM

Shane said:

Going insane with this!

I have a root site www.mydomainame.com

I then have a DNN install under the folder www.mydomainame.com/dnn/

I want to have client sites www.mydomainame.com/dnn/client1/

I know in DNN that sites setup as parent portals with the same name as a domain pointing to the DNN root will go to that client site.

SO if www.mydomainame.com was DNN root and my clients site was registered in DNN as cient1site.com

then their domain www.cleint1site.com pointed to my site should go to their DNN portal client1

I have been researching this for the lst 2 days and finally found your great article but it seems I still cant get this to work...

I am using the URL Rewrite wizard in IIS 7.5 i believe with DiscountASP.

I have tried so many things I am not sure now where to start.

Please can you help..

# April 3, 2013 5:49 PM

OWScott said:

Hi Shane,

For the initial part to get the site loading, would the following work?

<rewrite>

   <rules>

       <rule name="client1site.com" stopProcessing="true">

           <match url=".*" />

           <conditions>

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

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

           </conditions>

           <action type="Rewrite" url="\dnn\client1\{R:0}" />

       </rule>

   </rules>

</rewrite>

It's from the example in this blog post and just updated to use your paths. If not, what errors are you getting?

Part II of this blog post covers how the redirects and links work, but part I should at least allow most of it to work to confirm that you're on the right track.

# April 3, 2013 5:57 PM

Shane said:

Thanks for replying

I made a few corrections in line with your above settings and now it at least goes somehwere but i get this error.

I have set the portal alias in DNN to www.client1site.com upon browsing to that domain i get this error.

Server Error in '/DNN' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /dnn/client1/Home.aspx

And in the browser address bar i see: www.client1site.com/Home.aspx

# April 3, 2013 8:32 PM

OWScott said:

Shane,

This looks promising. It appears that the rule is working correctly. What happens if you visit www.client1site.com/dnn/client1/Home.aspx directly? Does that work? What happens if you try just www.client1site.com/dnn/client1/ or www.client1site.com/? It seems like the issue now is just that the default doc is off slightly.

# April 3, 2013 10:54 PM

OWScott said:

Hi Shane,

In that case it sounds like the error isn't with URL Rewrite but it's something with the default doc or the DNN install. I would first troubleshoot that error when you hit it directly, and after getting it working then move on to the URL Rewrite portion.

# April 5, 2013 9:19 AM

Shane said:

I only get that error when URL Rewrite rule is applied otherwise www.client1site.com/dnn/client1/Home.aspx works without rewrite rule.

Think I did not explain properly.

# April 6, 2013 4:12 AM

OWScott said:

Hi Shane,

That seems odd since the path in the rewrite looks like the correct path. Is there any chance that the binding to the site is catching on another site? For example the www and non-www sites are bound to a different site?

Just to be extra sure, what happens if you try these two URLs:

www.client1.com/.../Home.aspx

www.client1.com/Home.aspx

Does the top one work but the bottom one fails? Make sure that www.client1.com is bound to the correct IIS site, otherwise if it's bound to the default web site (or something like that) then it won't work as expected.

# April 10, 2013 9:23 AM

OWScott said:

Hi Shane,

I received your other post. Feel free to use the Contact link at the top of the page to contact me directly so we can discuss with your actual domain names. (I may be a bit slow responding since it arrives to an old email address. I haven't been successful in changing the notification email address)

# April 11, 2013 9:53 AM

OWScott said:

Hi Keshav,

This sounds like you just need to add a binding on the IIS site for each site (e.g. site1.kdsoftech.com). That will cause that site to catch the site.

If you're just seeing the IIS 7 page then it sounds like the default web site is catching the traffic using the wildcard binding. The wildcard binding is probably (all unassigned), port 80, blank host header.

Check out week 5 here for more info: dotnetslackers.com/.../LearnIIS7

# April 20, 2013 7:03 PM

Garry said:

I'm not sure if Rewrite is what I need, but here it is. I need to have users enter http://myphone.mycompany.com which is an IIS7.5 webpage hosted on webserver1.mycompany.com  I have a redirect setup on the webserver1 that forwards the users onto myphoneserver.mycompany.com/userlogin. I don't want users to have to try and remember the name of the actual phoneserver, and so having rewrite change what the user sees from myphoneserver.mycompany.com to myphone.mycompany.com

Is that even possible?

# June 25, 2013 7:21 PM

OWScott said:

Hi Garry,

There are a couple ways to do this. One with a redirect which will change the URL in the browser's address bar. The other is to use a reverse proxy which can make a call to a different server while maintaining the original URL in the browser. We can call that a rewrite (although a rewrite can be on a local server or to a remote server).

It really depends on your situation and setup, but yes, URL Rewrite (plus possibly ARR) are the right tools for the job.

# July 19, 2013 5:30 PM

Mujjammil said:

Hi,

Our website asks for certificate only when

https://www.fibiandclo.com/ is entered

rest all scenarios works fine. MY URL rewrite does not help.

Please help.

Regards,

tambolim@gmail.com

# September 20, 2013 10:13 AM

OWScott said:

Hi Mujjammil,

Your certificate is for fibiandclo.com without the www. If you publish your site with the www (which is common) then your best bet is to purchase another certificate for www.fibiandclo.com. Add both bindings and certificates to IIS and you won't get prompted.

Unfortunately this can't be fixed with URL Rewrite since the binding occurs before URL Rewrite gets a handle on the request.

# September 24, 2013 11:23 AM

Basilios said:

I am trying to rewrite a url for an international site. I own both domains. so for examples. currently. www.mysite.com.cn redirects to www.mysite.com/cn/... but i want it to still go to the same subdomain but the url to still say www.mysite.com.cn/cn/...

Any thoughts?

# October 23, 2013 3:32 PM

OWScott said:

Hi Basilios,

In your action you can use {HTTP_HOST} rather than www.mysite.com. That will use the actual domain name that the user visited using. Is that what you are looking for?

# October 24, 2013 1:35 PM

Basilios said:

Hi Scott, thanks for the response. I have been trying to use {HTTP_HOST} as a condition. Is that what you mean? So The actions should not be redirect or rewrite? How would i use {HTTP_HOST} as an action?

# October 25, 2013 9:26 AM

OWScott said:

Hi Basilios,

I'm not positive if I understand your requirements. I'll start with an example and then if you can explain further I should be able to help with a rule.

Here's a way to run your CN site from a subfolder and have your URL stay at www.mysite.cn.

<rule name="Cn runs from subfolder" patternSyntax="Wildcard">

   <match url="*" />

   <conditions>

       <add input="{HTTP_HOST}" pattern="www.mysite.cn" />

       <add input="{URL}" pattern="/cn/*" negate="true" />

   </conditions>

   <action type="Rewrite" url="/cn/{R:0}" />

</rule>

If you did want to use the domain name in the action you can do something like this:

   <action type="Redirect" url="http://{HTTP_HOST}/cn/{R:0}" />

But I'm not sure now if that's what you're looking for. If you can explain further I can continue to help.

# October 25, 2013 10:06 AM

Basilios said:

Scott thanks so much for your help.

Here is what I have so far.

When a user types in www.mysite.com.cn it goes to my site root which is www.mysite.com.cn/Pages/Default.aspx

This is the English site. So I want it to got to

www.mysite.com/CN/Pages/Default.aspx which is the China version. Now i was able to do that with a redirect but i would like the URL to rewrite or redirect as www.mysite.com.cn/CN/Pages/Default.aspx

I was able to get this to work like this (thanks to one of your articles!)…

<rule name="Cn runs from subfolder" patternSyntax="Regular Expressions">

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

  <conditions>

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

      <add input="{PATH_INFO}" pattern="Pages/default.aspx" negate="true" />

  </conditions>

  <action type="Redirect" url="/cn/" />

</rule>

However the problem now is that there are other pages that have the PATH Pages/default.aspx so then it loops back to the home page. Any other way I can rewrite that condition?

# October 29, 2013 10:37 AM

OWScott said:

Hi Basilios,

What happens if you use a Rewrite rather than a redirect, and set it to "/cn/{R:0}".

Also change the {PATH_INFO} pattern to be "^/cn".

That will preserve the original domain name which has a nice little benefit, and the {R:0} will preserve the original path rather than funneling everything to the default doc.

# November 1, 2013 5:25 PM

Vishal Chanana said:

I puzzled with godaddy windows hosting

But your web.config code help me to redirect main domain to subfolder

# February 11, 2014 2:58 PM

Morten said:

Thanks for an excellent guide! This saved me hours of pain :)

# February 20, 2014 9:22 AM

Jeff said:

Your guide/walkthrough was the best out there - thank you.

I have a typical subdomain: master/site2/default.aspx type structure. I implemented the rules in the web.config of my master folder and got them working. But they quit working when I moved the <rewrite> section into the site2's web.config (and deleted them from the master).

If I download the site2 web.config, I can see them - so I know I'm changing the right one. Any thoughts on what to look for?

# March 20, 2014 1:56 PM

OWScott said:

Hi Jeff,

That should work in a subfolder too. What I suggest is to create a simple 'break' test which uses URL Rewrite to simply break the site or to show a different status if testing from your IP address. This is a way to confirm that URL Rewrite is installed and working as expected for your site and that the page visit reaches your site2 folder. You only need to keep the break test live for a few seconds.

I assume this is on the same server (or probably a subfolder of the same site) and that URL Rewrite is working. In that case, my suggestion is to simplify the rule and make sure that it's catching. Maybe the condition is too restrictive.

Also, make sure that the original domain name is bound to the site with the rules. The rules won't kick in unless the visit is to the site with the rules. And make sure that other rules aren't running first on the master folder that prevent the rules in site2 from running.

# March 22, 2014 1:03 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)