asp.net – IIS URL重写:强制规范主机名和HTTP到HTTPS重定向

我在web.config文件中使用这两个规则:
<rule name="Enforce canonical hostname" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" negate="true" pattern="^www\.example\.com$" />
      </conditions>
      <action type="Redirect" url="https://www.example.com/{R:1}" redirectType="Permanent" />
    </rule>
    <rule name="HTTP to HTTPS redirect" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
    </rule>

有了这两个规则,我得到以下重定向工作:

> http://www.example.com —> https://www.example.com
> http://example.com—> https://www.example.com
> https://example.com —>这不能重定向https://www.example.com …为什么?

解决方法

不知道你还在寻找答案,但是这里.经过一番搜索,试错,我发现以下规则成功.我遇到的大多数例子在模式匹配方面是不必要的复杂的,并引入了阻止规则按预期工作的其他变量.以下规则可以应用于任何网站,没有什么是硬编码,因此它应该始终是一个直接的复制和粘贴作业:
<rule name="Redirect to WWW" stopProcessing="true" >
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^www\." negate="true"/>
    </conditions>
    <action type="Redirect" url="https://www.{HTTP_HOST}{HTTP_URL}" redirectType="Permanent" appendQueryString="false" />
</rule>
<rule name="Redirect to HTTPS">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTPS}" pattern="OFF"/>
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{HTTP_URL}" redirectType="Permanent" appendQueryString="false" />
</rule>

需要注意的两个事项:redirectType =“Permanent”将导致规则被应用,直到浏览器的历史/缓存清空;这应该是一件好事,因为浏览器会进行下一步的工作.此外,appendQueryString =“false”是必需的,因为{HTTP_URL}服务器变量已经包含完整的querystring;认情况下该选项为“true”,并在此处导致重复的查询字符串.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....