我写了一个小函数来建立当前的网站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吗?有必要检查一下协议吗?

谢谢你!


当前回答

在我的系统上使用Rid Iculous的答案做了一个函数。

function site_protocol() {
    if(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')  return $protocol = 'https://'; else return $protocol = 'http://';
}

希望能有所帮助

其他回答

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

一些变化:

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

这是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改为您的域名。

对于除IIS之外的任何系统,这就足够定义站点的URL了:

$siteURL='http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].'/';

or

$siteURL='http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].'/';

这取决于你到底想要什么: HTTP_HOST vs. SERVER_NAME

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

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