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

