首页 > 解决方案 > 检查cookie是否存在,否则重定向到url IIS

问题描述

我想为基于 HTTP_COOKIE 的 URL 设置 IIS 重定向

cookie-nameToken和 value 是动态的。

我尝试了以下规则,但每个规则都给了我错误-

<rule name="redirect based by cookie" stopProcessing="true">
<match url=".*" />
<conditions>
    <add input="{HTTP_COOKIE}" pattern="_xx=HCjdskfds==" />
    <add input="{HTTP_HOST}" pattern="xxx.yyy.com" />
</conditions>
<action type="Redirect" url="http://zzz.kkk.com/{R:0}" />
</rule>

<rule name="Route Base On Cookie" stopProcessing="true">
<match url="^(.*)" />
<conditions>
   <add input="{HTTP_COOKIE}" pattern="foo=(.*?);" />
</conditions>
<action type="Rewrite" url="http://{C:1}/{R:0}" />
</rule>

以上规则都将在我的域上的每个 url 上给出错误

错误描述

我在这里尝试的是如果该页面不包含cookieToken到错误页面/登录页面则重定向

提前致谢........

标签: iisiis-8.5

解决方案


目标:如果用户的请求中不存在 cookie,则重定向用户。

解决方案:

  • 添加到项目根目录下 IIS 的 web.config
  • 匹配每个网址
  • 假设 cookie 是CookieName=any_value
  • 匹配模式使用正则表达式检查任何值的 cookie 名称
  • 用作negate="true"非运算符;如果未找到 cookie
  • redirectType是可选的。默认是 301,Found是 302。
<configuration>
  <system.webServer>
    <rewrite>
      <rules>

        <rule name="Redirect if Cookie is present" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_COOKIE}" pattern="CookieName=*" negate="true" />
          </conditions>
          <action type="Redirect" url="https://www.my-domain.com/login" redirectType="Found" />
        </rule>

      </rules>
    </rewrite>
  </system.webServer>
</configuration>

此规则基本上是具有名称的 cookie 的通配符,CookieName因此如果具有该名称的 cookie 有任何值(它存在),那么您将不会被重定向。如果未找到 cookie,您将被重定向。

一个警告是,没有办法识别 HttpOnly cookie 与浏览器设置的 cookie ...... :(

资料来源:


推荐阅读