Nginx:使用标头检测 HTTPS 连接

Jas*_*sta 5 nginx https

在我的负载平衡器上,我终止了与 Nginx 的 HTTPS 连接,然后将请求代理到同样由 Nginx 支持的 Web 服务器之一。

在 fastcgi_params 中的负载均衡器上,我有:

fastcgi_param   HTTPS   $https;
Run Code Online (Sandbox Code Playgroud)

在 Web 服务器上有一个只能通过 HTTPS 访问的站点。如何检测是否设置了 HTTPS 参数以及是否重定向到站点的安全版本?

Tef*_*tin 17

如果我理解正确的话,你的设置是这样的:

客户端-(http/https)-> nginx(前)-(http)-> nginx(后)-(fastcgi)-> 应用

实际上有 3 个不同的地方可以进行重定向:

在您的前端 Nginx 服务器上,您可以在需要时进行重定向:

if ( $https != 'on' ) {
  return 301 https://$host$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

如果前端的 Nginx 服务器无法做到这一点,则必须携带所用协议的信息来支持 Nginx 实例。通常的方法是使用 X-Forwarded-Proto 标头。您应该在前端 Nginx 服务器上的适当位置添加:

proxy_set_header X-Forwarded-Proto $scheme;
Run Code Online (Sandbox Code Playgroud)

然后,您可以在后端 Nginx 服务器中进行重定向:

if ( $http_x_forwarded_proto != 'https' ) {
  return 301 https://$host$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

显然,您也可以处理应用程序内部的重定向。您应该在应用程序中有可用的 X-Forwarded-Proto 标头,或者您可以将其设置为 fastcgi 参数:

http {} 中的某处

map $http_x_forwarded_proto $fe_https {
  default off;
  https on;
}
Run Code Online (Sandbox Code Playgroud)

和额外的映射:

fastcgi_param   HTTPS $fe_https;
Run Code Online (Sandbox Code Playgroud)

就个人而言,我认为重定向应该尽可能早地在链中进行。