nginx负载转发源请求http/https:X-Forwarded-Proto及nginx中的转发报头
今天在排查服务器的问题时最后定位到服务器因为经过了运维这一层的处理,转发过来的请求不管用户请求的是https还是http,我们的proxy服务器收到的都是80端口上的http。于是联系相关部门了解有没有现成的可用的这样一个字段来获得这个值。公司用的也是标准报头,即X-Forwarded-Proto。
X-Forwarded-Proto(XFP)报头是用于识别协议HTTP或HTTPS的,即用户客户端
实际连接到代理或负载均衡的标准报头。
后端的服务器如果要确定客户端和负载平衡器之间使用的协议,可以使用X-Forwarded-Proto
请求标头。
nginx是支持读取非nginx标准
的用户自定义header的,但是需要在http或者server下使用underscores_in_headers
开启header的下划线支持,然后使用proxy_set_header
向后端服务器发送字段X-Forwarded-Proto
。
#proxy_set_header上下文:http, server, location。语法:
proxy_set_header field value;
#默认值:
proxy_set_header Host $proxy_host;
proxy_set_header Connection close;
#开启header的下划线支持:
underscores_in_headers on;
#设置向后端proxy发送X-Forwarded-Proto字段
proxy_set_header X-Forwarded-Proto $http_X_Forwarded_Proto;
proxy_set_header X-Real-IP $remote_addr;
在后端的服务器,使用$http_X_Forwarded_Proto
接收的,也可以使用小写比如$http_x_forwarded_proto
来接收,前面都需要加上http_
。