使用IIS URL重写从地址中删除www的正确方法

问题描述:

使用IIS URL重写从网址中删除www子域的最佳方法是什么?

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

如果您希望它与任何主机名一起使用(而不是将其硬编码到规则中),则需要执行以下操作:

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>

在重定向操作中,{C:1}包含条件中的第二个捕获组,而{R:0}包含规则中的任何内容(路径). appendQueryString ="true"还将任何查询字符串附加到重定向(如果存在).但是请记住,由于没有将这些URL哈希传递给服务器,因此任何URL哈希(如果存在)都将在此过程中丢失.

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.