IIS 7 Canonical URL redirect

2020-07-09 03:25发布

问题:

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?

回答1:

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



回答2:

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>


回答3:

I would also suggest you another variant for testing in local environment:

  1. Add to c:\Windows\System32\drivers\etc\hosts:

127.0.0.1 www.example.com

  1. In IIS Manager select site and right click -> Edit bindings.. -> Add..

  2. Enter host name: www.example.com

  3. Open cmd and run iisreset

Now you are able to use www.example.com in browser which is mapped to localhost