我的目标是在 IIS/Azure 的 web.config 文件中添加规则,以成功重定向以下客户端请求示例:
HTTPS 重定向:
- 来自:example.com
- 致:https://example.com
无 www 和 HTTPS 重定向:
- 来自:www.example.com
- 致:https://example.com
无 www、HTTPS 重定向和维护路径:
来自:www.example.com/examplepage
这是我到目前为止所做的,仅实现了第 1 点和第 2 点。如果访问者直接登陆子页面,他们不会被重定向到非 www,也不会被重定向到 HTTPS。
<rule name="Redirect to https">
<match url="(.*)"/>
<conditions>
<add input="{HTTPS}" pattern="Off"/>
<add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}"/>
</rule>
<rule name="Canonical Hostname" stopProcessing="false">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
</conditions>
<action type="Redirect" url="https://{C:2}{REQUEST_URI}" redirectType="Permanent" />
</rule>
我已经用尽了多个搜索结果页面和多个 StackOverflow 问题,但没有任何运气 - 它们都 promise 能够实现第三点(重定向到非 www、HTTPS 页面并维护路径)但它们对我不起作用。
感谢您花时间阅读本文!
最佳答案
我发现了这个问题,部分原因是我提出问题的方式(抱歉,StackOverflowers!)。
问题在于规则的顺序。我已将以下(新)规则按以下顺序放在规则部分的顶部,供将来遇到此问题的人使用。现在,它重定向到 HTTPS,不带 www,并维护客户端请求的路径。
<rule name="Canonical Hostname" stopProcessing="false">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
</conditions>
<action type="Redirect" url="http://{C:2}{REQUEST_URI}" redirectType="Permanent" />
</rule>
<rule name="Force HTTPS" enabled="true">
<match url="(.*)" ignoreCase="false" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
关于redirect - IIS/Azure web.config 文件的简单规则将流量重定向到非 www HTTPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29360467/