PHP - 头位置重定向:HTTPS到HTTPS,HTTP到http

问题描述:

如何正确使用头功能,所以PHP - 头位置重定向:HTTPS到HTTPS,HTTP到http

header("location: http://".$_SERVER['HTTP_HOST']."/?para=abc"); //for http 

header("location: https://".$_SERVER['HTTP_HOST']."/?para=abc"); //for https 

可如果可能的话写在1串?

.htaccess文件将负责将所有http页面重定向到https而不会造成任何问题,但我相信在header("location:...)中为http/https页面使用正确的语法是有意义的,因此它适用于所有浏览器。

$protocol='http'; 
if (isset($_SERVER['HTTPS'])) 
    if (strtoupper($_SERVER['HTTPS'])=='ON') 
    $protocol='https'; 

header("location: $protocol://".$_SERVER['HTTP_HOST']."/?para=abc"); 

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != '') { 
    header("location: https://".$_SERVER['HTTP_HOST']."/?para=abc"); 
} else { 
    header("location: http://".$_SERVER['HTTP_HOST']."/?para=abc") 
} 

这应该适用于Apache的,至少。

你可以做这样的事情隔离协议类型:

$protocol = isset($_SERVER['HTTPS']) and 'https' or 'http' 

然后

header("location: $protocol://".$_SERVER['HTTP_HOST']."/?para=abc"); 

你也使用下面的代码:

header("Location: //www.google.com"); 
+0

这并不为我工作。它将URL附加到当前的根网址。 – cederlof 2017-02-05 19:41:14

你可以得到通过以下代码协议:

$protocol = strtolower(substr($_SERVER[ 'SERVER_PROTOCOL' ], 0, 5)) == 'https' ? 'https' : 'http'; 

,然后重定向这样

header('location: ' . $protocol . '://' . $_SERVER[ 'HTTP_HOST' ] . '/?para=abc');