我写了一个小函数来建立当前的网站url协议,但我没有SSL,不知道如何测试它是否在https下工作。你能告诉我这对吗?

function siteURL()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'].'/';
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

有必要像上面那样做吗?或者我可以像上面那样做吗?:

function siteURL()
{
    $protocol = 'http://';
    $domainName = $_SERVER['HTTP_HOST'].'/'
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

在SSL下,即使锚标记url使用http,服务器不自动将url转换为https吗?有必要检查一下协议吗?

谢谢你!


当前回答

在代理的情况下,SERVER_PORT可能不会给出正确的值,所以这是为我工作-

$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 || $_SERVER['HTTP_X_FORWARDED_PORT'] == 443) ? "https://" : "http://"

其他回答

它不是自动的。上面的函数看起来不错。

这是HTTPS或HTTP的最佳解决方案:

<?php
$protocol = '//';  
$site_url = $protocol.$_SERVER["HTTP_HOST"];
?>

但不能显示https或http,所以它只用于链接您的网站内容,如图像等。

如果想在https中重定向你的网站,在.htaccess文件中添加以下代码:

<IfModule mod_rewrite.c>
 RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
 RewriteRule ^(.*)$ https://www.your-domain.com$1 [L]
</IfModule>

将www.your-domain.com改为您的域名。

使用这个服务器变量获取协议细节:

 $scheme = $_SERVER['REQUEST_SCHEME'] . '://';
 echo $scheme; //it gives http:// or https://

注意,这个服务器变量是不可靠的。欲了解更多信息,请查看: $_SERVER['REQUEST_SCHEME']是否可靠?

$protocal = 'http';
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || $_SERVER['HTTPS'] == 'on') {$protocal = 'https';}


echo $protocal;

在代理的情况下,SERVER_PORT可能不会给出正确的值,所以这是为我工作-

$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 || $_SERVER['HTTP_X_FORWARDED_PORT'] == 443) ? "https://" : "http://"