You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HA Proxy后端C# HttpContext获取URL时HTTPS被转为HTTP的问题

问题原因

HAProxy作为SSL终止代理,前端接收HTTPS请求后,会转换为HTTP协议转发到后端的80端口。.NET的HttpContext.Current.Request.Url默认根据后端服务器收到的请求协议(HTTP)生成URL,所以即便前端是HTTPS,返回的地址仍以HTTP开头。虽然你在HAProxy中添加了X-Forwarded-Proto: https头,但.NET默认不会自动使用这个头来修正请求的协议。

解决方案

推荐优先采用第一种.NET应用配置的方式,适配反向代理场景更灵活:

方式1:让ASP.NET Framework识别X-Forwarded-Proto头

方法A:通过URL Rewrite模块配置(web.config)

在项目的web.config中添加以下配置,让应用信任反向代理的头信息,自动修正请求协议:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Force HTTPS from X-Forwarded-Proto">
        <match url=".*" />
        <conditions>
          <add input="{HTTP_X_FORWARDED_PROTO}" pattern="https" />
        </conditions>
        <serverVariables>
          <set name="HTTPS" value="on" />
          <set name="SERVER_PORT" value="443" />
        </serverVariables>
        <action type="None" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

方法B:在Global.asax中手动修正

如果不想使用URL Rewrite模块,可在Global.asax的Application_BeginRequest事件中添加代码:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var forwardedProto = Request.Headers["X-Forwarded-Proto"];
    if (!string.IsNullOrEmpty(forwardedProto) && forwardedProto.Equals("https", StringComparison.OrdinalIgnoreCase))
    {
        Request.ServerVariables["HTTPS"] = "on";
        Request.ServerVariables["SERVER_PORT"] = "443";
    }
}

修改完成后,HttpContext.Current.Request.Url.AbsoluteUri就能正确返回HTTPS开头的地址。

方式2:优化HAProxy配置(辅助)

当前HAProxy中的http-request add-header X-Forwarded-Proto https if { ssl_fc }可改为覆盖式设置,避免重复添加头信息:

http-request set-header X-Forwarded-Proto %[ssl_fc,map(0:http,1:https)]

这样无论请求是HTTP还是HTTPS,都会正确设置X-Forwarded-Proto头,配合.NET端的配置效果更佳。

验证

修改配置后,重启HAProxy或重新部署.NET应用,访问https://app02.mywebsite.com.br/teste.aspx,即可看到返回的URL以HTTPS开头。

内容的提问来源于stack exchange,提问作者Vander Batista

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:36:11