用 PHP 从 HTTP 重定向到 HTTPS

我在一个购物车网站上工作,我想重定向用户到一个 HTTPS 页面时,他输入他的帐单细节和维护下一个页面的 HTTPS 连接,直到他退出。

为了做到这一点,我需要在服务器上安装什么(我正在使用 Apache) ,以及如何从 PHP 实现这一重定向?

204157 次浏览

你可以随时使用

header('Location: https://www.domain.com/cart_save/');

重定向到保存 URL。

但是我建议使用.htaccess 和 Apache 重写规则。

Try something like this (should work for Apache and IIS):

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}

使用 IIS 上的 PHP 从 HTTP 重定向到 HTTPS

我在重定向到 HTTPS 以便在 Windows 服务器上工作时遇到了麻烦 它运行的是 微软互联网资讯服务的第6版 used to working with Apache on a Linux host so I turned to the Internet for 帮助,这是排名最高的堆栈溢出问题时,我搜索 但是,所选择的答案不起作用 为了我。

After some trial and error, I discovered that with IIS, $_SERVER['HTTPS'] is set to off for non-TLS connections. I thought the following code should 帮助任何其他 IIS 用户谁来到这个问题通过搜索引擎。

<?php
if (! isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off' ) {
$redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $redirect_url");
exit();
}
?>

编辑 : 从另一个 堆栈溢出答案, 更简单的解决方案是检查 if($_SERVER["HTTPS"] != "on")

这是一个很好的方法:

<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' ||
$_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>

On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:

if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}