普通网友 2019-06-08 14:21
浏览 75
已采纳

这是可能的PHP协议基地网址

So - I have made a website with php includes in my header I have the following

<?php
$protocol = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
$path = $protocol . '://domain.com/';
?>

but for some reason when I put www. in the URL bar, it breaks the site I even have a 301 direct in cpanel

is there a way to add www or no www to this?

  • 写回答

1条回答 默认 最新

  • duanhuoyao7011 2019-06-08 15:31
    关注

    It's possible to have a function for absolute http(s) path, the best way is check if server responses as HTTP or HTTPS and rewrite the php code according to new path...

    check.php

    <?php
      // Checking for HTTP or HTTPS
      function check_protocol() {
        $isSecure = false;
        if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
          $isSecure = true;
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) == 'on') {
          $isSecure = true;
        }
        return $isSecure;
      }
      $protocol = check_protocol() ? 'https://' : 'http://';
      $host = $protocol . $_SERVER['HTTP_HOST'];
    ?>
    

    Usage is simple:

    <?php
      include("check.php");
      echo $host;
      // it prints http://www.example.com or https://www.example.com
    ?>
    

    or using the absolute path thanks to $_SERVER['DOCUMENT_ROOT']:

    <?php
      include($_SERVER['DOCUMENT_ROOT'] . "/php/check.php");
      echo $host;
      // it prints http://www.example.com or https://www.example.com
    ?>
    

    In addition to this may be useful a redirect using .htaccess if the server is hosted on Apache server...

    I found useful this rule for my .htaccess:

    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
    

    This rule may not work on different server configuration... read this thread for getting more info about the most different sever configuration...

    I hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大