PHP(CodeIgniter)301将http重定向到https



如果站点有SSL证书,我将尝试强制使用https。我可以确认代码确实有效,因为它确实进行了重定向,但它最终会无限循环,尽管我不知道为什么。只有当服务器端口不是443时才应该进行重定向,我认为在第一次重定向之后,用户应该使用端口443。

这是我的密码;

// If they're using a masking domain and they own an SSL certificate, force SSL
$this->db->where('client_id', $client['client']);
$result = $this->db->get('ssl_certs')->row_array();
// only run this function if there is a date in this field
if (!empty($result['ssl_completed_date']))
{
// if they're not using https, redirect them to https
if($_SERVER['SERVER_PORT'] != 443)
{
$redirect = 'https://www.' . $_SERVER['HTTP_HOST'] . '/website';
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
}

如有任何帮助,我们将不胜感激!

需要注意的几件事:

1( 我相信返回的值是一个字符串,而不是一个数字。(未检查,但需要验证(。不管怎样,这不会有什么不同,因为你没有这么做但放松!=

2( 手册,位于"server_port"下(http://php.net/manual/en/reserved.variables.server.php)状态

注意:在Apache 2下,必须设置UseCanonicalName=On以及UseCanonical PhysicalPort=On才能获得物理(真实(端口,否则,该值可能会被欺骗,它可能会也可能不会返回物理端口值。在依赖安全性的上下文中依赖此值是不安全的。

3(最好使用$_SERVER数组的"HTTPS"。详情见同一页。

4( 如果在负载均衡器后面,您还需要检查$_SERVER['HTTP_X_FORWARDED_PROTO']

if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$isSecure = ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
} else {
$isSecure = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] == 1));
}

最新更新