Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS 7 Canonical URL redirect

I would like to make a website always have www in the address, and enforce it via IIS rewrite.

For example, test.com would become www.test.com.

The typical example rewrite rule is:

<rule name="Canonical Host Name" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{HTTP_HOST}" negate="true" pattern="^www\.test\.com$" />
  </conditions>
  <action type="Redirect" url="http://www.test.com/{R:1}" redirectType="Permanent" />
</rule>

However this requires me to enter the full url of my website. It will not work for development and staging environments that have URLs like www.test.dev and www.test.stage.

Is it possible to create an IIS Rewrite rule that will handle all of those cases?

like image 558
Evan Avatar asked May 02 '11 12:05

Evan


2 Answers

I have another solution for you:

<rule name="Canonical domain name" enabled="true" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$" />
    </conditions>
    <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent" />
</rule>
like image 65
Seyed Mohammad Hossein Mayboud Avatar answered Sep 28 '22 17:09

Seyed Mohammad Hossein Mayboud


You're right that the full URL needs to be in the web.config. You have options though.

  1. You can use a config transform to make the regular expression match the correct environment.

  2. There doesn't seem to be any harm if you include all three URL rewrite rules in your web.config. It sounds like your environments are isolated so each environment would only ever match one of the rules. That can clutter your web.config, but not horribly.

I'd go with option 1. You can find information on config transforms here: http://msdn.microsoft.com/en-us/library/dd465326.aspx

like image 37
matt.mercieca Avatar answered Sep 28 '22 15:09

matt.mercieca