在 PHP 中检测 HTTPS 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/452375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:47:07  来源:igfitidea点击:

Detecting HTTPS requests in PHP

phpapachehttps

提问by deadprogrammer

The problem that I am having has to do with the need to keep some urls of a website protected by HTTPS and the rest kicked to HTTP.

我遇到的问题与需要保持网站的某些 url 受 HTTPS 保护有关,而其余的则被踢到 HTTP。

Normally, you have $_SERVER['HTTP_HTTPS']or $_SERVER['HTTPS'](depending on your flavor of Apache). You also can check the port - it's 80 for normal traffic and 443 for HTTPS.

通常,您有$_SERVER['HTTP_HTTPS']$_SERVER['HTTPS'](取决于您的 Apache 风格)。您还可以检查端口 - 正常流量为 80,HTTPS 为 443。

My problem is that the certificate sits on the loadbalancer, and all these variables are unavailable, and the webserver sees http://www.foo.comon port 80. One way to fix this is to tell the loadbalancer to send the traffic on a different port, but I wonder if there are other ways to detect HTTPS coming from the load balancer?

我的问题是证书位于负载均衡器上,并且所有这些变量都不可用,并且网络服务器在端口 80 上看到http://www.foo.com。解决此问题的一种方法是告诉负载均衡器将流量发送到一个不同的端口,但我想知道是否有其他方法可以检测来自负载均衡器的 HTTPS?

采纳答案by hayalci

If the load balancer is the other end of the SSL connection, you cannot get any more info than the load balancer explicitly provides. I would go for adding a http header, it may already be doing that, dump all the HTTP headers and look.

如果负载均衡器是 SSL 连接的另一端,则除了负载均衡器明确提供的信息外,您无法获得更多信息。我会去添加一个 http 标头,它可能已经这样做了,转储所有的 HTTP 标头并查看。

As another solution, you can do the redirection on the load balancer based on URL.

作为另一种解决方案,您可以根据 URL 在负载均衡器上进行重定向。

回答by mrucci

If anybody has the same issue behind an Amazon AWS Elastic Load Balancer, the solution is simple because the $_SERVERvariable will include:

如果有人在 Amazon AWS Elastic Load Balancer 背后遇到同样的问题,解决方案很简单,因为$_SERVER变量将包括:

[HTTP_X_FORWARDED_PORT] => 443
[HTTP_X_FORWARDED_PROTO] => https

So, to get the protocol, you could use:

因此,要获取协议,您可以使用:

function getRequestProtocol() {
    if(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']))
        return $_SERVER['HTTP_X_FORWARDED_PROTO'];
    else 
        return !empty($_SERVER['HTTPS']) ? "https" : "http";
}

回答by Elyoukey

the $_SERVER['HTTP_X_FORWARDED_PROTO'] seems to be a good solution for joomla users because if your loadbalancer does the rediretion and you set the force_ssl setting to 1 or 2 then you will end in an infinite loop because joomla always sees http:

$_SERVER['HTTP_X_FORWARDED_PROTO'] 对于 joomla 用户来说似乎是一个很好的解决方案,因为如果您的负载均衡器执行重定向并且您将 force_ssl 设置设置为 1 或 2,那么您将以无限循环结束,因为 joomla 总是看到 http: