php - header location redirect: https to https, ht

2019-05-23 07:12发布

How do I properly use header function, so

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

and

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

could be written in 1 string if possible?

.htaccess file will take care of all http pages to be redirected to https with no problem, but I believe it makes sense to use a proper syntax for http/https pages in header("location:...), so it is correct for all browsers.

5条回答
倾城 Initia
2楼-- · 2019-05-23 07:28
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != '') {
    header("location: https://".$_SERVER['HTTP_HOST']."/?para=abc");
} else {
    header("location: http://".$_SERVER['HTTP_HOST']."/?para=abc")
}

This should work for Apache, at least.

查看更多
我只想做你的唯一
3楼-- · 2019-05-23 07:28

You can isolate the protocol-type by doing something like this:

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

Then

header("location: $protocol://".$_SERVER['HTTP_HOST']."/?para=abc");
查看更多
The star\"
4楼-- · 2019-05-23 07:32
$protocol='http';
if (isset($_SERVER['HTTPS']))
  if (strtoupper($_SERVER['HTTPS'])=='ON')
    $protocol='https';

header("location: $protocol://".$_SERVER['HTTP_HOST']."/?para=abc");
查看更多
我只想做你的唯一
5楼-- · 2019-05-23 07:37

You could also use the following code:

header("Location: //www.google.com");
查看更多
ら.Afraid
6楼-- · 2019-05-23 07:38

You can get the protocol by following code:

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

and then redirect like this

header( 'location: ' . $protocol . '://' . $_SERVER[ 'HTTP_HOST' ] . '/?para=abc' );
查看更多
登录 后发表回答