负载均衡SSL卸载场景下URL Rewrite的HTTPS检测与重定向问题
正确的URL Rewrite规则配置方案
针对负载均衡SSL卸载场景下,依赖自定义x-ssl请求头做协议重定向的需求,以下是具体的IIS URL Rewrite规则配置:
规则1:存在x-ssl头时,强制重定向到HTTPS
当负载均衡转发的请求带有x-ssl头(说明原始请求是HTTPS),且当前应用收到的是HTTP请求时,自动重定向到HTTPS地址:
<rule name="Redirect to HTTPS if x-ssl exists" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAll"> <add input="{HTTP_X_SSL}" pattern=".+" /> <add input="{SERVER_PORT}" pattern="^80$" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /> </rule>
{HTTP_X_SSL}:IIS会将自定义请求头x-ssl转换为大写前缀的服务器变量,pattern=".+"表示只要该头存在(有任意值)即匹配。{SERVER_PORT}匹配80,确保当前是负载均衡转发的HTTP请求。- 重定向地址保留原域名
{HTTP_HOST}和请求路径{R:1},避免丢失业务路径。
规则2:不存在x-ssl头时,强制重定向到HTTP
当请求无x-ssl头(说明原始请求是HTTP),且当前应用收到的是HTTPS请求(如绕过负载均衡的直接访问)时,重定向到HTTP地址:
<rule name="Redirect to HTTP if x-ssl not exists" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAll"> <add input="{HTTP_X_SSL}" pattern="^$" /> <add input="{SERVER_PORT}" pattern="^443$" /> </conditions> <action type="Redirect" url="http://{HTTP_HOST}/{R:1}" redirectType="Permanent" /> </rule>
pattern="^$"表示x-ssl头不存在或值为空。{SERVER_PORT}匹配443,确保当前是HTTPS请求场景。
额外优化:让.NET应用识别原始协议
如果需要让.NET应用内部的Request.IsSecureConnection能正确判断原始请求协议,可添加服务器变量重写规则,将HTTPS变量与x-ssl头关联:
先在web.config中允许修改HTTPS服务器变量:
<system.webServer> <rewrite> <allowedServerVariables> <add name="HTTPS" /> </allowedServerVariables> </rewrite> </system.webServer>
再添加变量重写规则:
<rule name="Set HTTPS variable from x-ssl" stopProcessing="false"> <match url=".*" /> <conditions> <add input="{HTTP_X_SSL}" pattern=".+" /> </conditions> <serverVariables> <set name="HTTPS" value="ON" /> </serverVariables> </rule>
这样.NET应用内部就能通过原生API获取正确的协议状态,无需额外修改业务代码。
内容的提问来源于stack exchange,提问作者Marcus
相关产品推荐
相关产品推荐

