Proper method to remove www from address using IIS URL Rewrite

我怕爱的太早我们不能终老 提交于 2019-12-17 11:01:04

问题


What is the optimal way to remove the www subdomain from a url using IIS URL Rewrite?


回答1:


If you want it to work with any hostname (not hardcoding it into the rule), you'd want to do something like this:

<rule name="Remove www" stopProcessing="true">
  <match url="(.*)" ignoreCase="true" />
  <conditions logicalGrouping="MatchAll">
    <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
  </conditions>
  <action type="Redirect" url="http://{C:1}/{R:0}" appendQueryString="true" redirectType="Permanent" />
</rule>

in the redirect action, the {C:1} contains the second capturing group in the condition, whereas the {R:0} contains whatever was in the rule (the path). appendQueryString="true" will also append any querystring to the redirect (if present). Keep in mind though, that any url hashes, if present, will be lost in the process since those don't get passed to the server.




回答2:


IIS does it automatically for you:

Select site > URL rewrite > new rule > Canonical Host Name :)




回答3:


The following one should work :

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Remove WWW" stopProcessing="true">
        <match url="^(.*)$" />
        <conditions>
          <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
        </conditions>
        <action type="Redirect" url="http://www.example.com{PATH_INFO}" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>



回答4:


To do a redirect that will work for both http and https the following can be used

    <rewrite>
        <rules>
            <rule name="Lose the www" enabled="true" stopProcessing="true">
                <match url="(.*)" ignoreCase="true"/>
                <conditions logicalGrouping="MatchAll">
                    <add input="{HTTP_HOST}" pattern="^www\.(.*)$"/>                    
                </conditions>
                <action type="Redirect" redirectType="Permanent" url="{SchemeMap:{HTTPS}}://{C:1}/{R:1}" appendQueryString="true" />
            </rule>
        </rules>
        <rewriteMaps>
            <rewriteMap name="SchemeMap">
                <add key="on" value="https" />
                <add key="off" value="http" />
            </rewriteMap>
        </rewriteMaps>
    </rewrite>


来源:https://stackoverflow.com/questions/7368665/proper-method-to-remove-www-from-address-using-iis-url-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!