Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

iis - web.config redirect non-www to www

I need to redirect non-www urls to www url for both http and https urls. I tried following rules in web.config.

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

<rule name="Redirect to WWW https" stopProcessing="true">
<match url=".*" />
<conditions>
    <add input="{HTTPS}" pattern="^domain.com$" />
</conditions>
<action type="Redirect" url="https://www.domain.com/{R:0}" redirectType="Permanent" />

It works perfectly for non-ssl url but in case of ssl it redirect from https://domain.com to http://www.domain.com

Please help me to correct my rules.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a safer rule that works for both Match Any and Match All situations, you can use the Rewrite Map solution. It’s a perfectly good solution with the only drawback being the ever so slight extra effort to set it up since you need to create a rewrite map before you create the rule. In other words, if you choose to use this as your sole method of handling the protocol, you’ll be safe.

You can create a Rewrite Map called MapProtocol, you can use {MapProtocol:{HTTPS}} for the protocol within any rule action.

<rewrite>
  <rules>
    <rule name="Redirect to www" stopProcessing="true">
      <match url="(.*)" />
      <conditions trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^domain.com$" />
      </conditions>
      <action type="Redirect" 
        url="{MapProtocol:{HTTPS}}://www.domain.com/{R:1}" />
    </rule>
  </rules>
  <rewriteMaps>
    <rewriteMap name="MapProtocol">
      <add key="on" value="https" />
      <add key="off" value="http" />
    </rewriteMap>
  </rewriteMaps>
</rewrite>

Reference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...