【问题标题】:Redirect non-www and www http requests to https://www将非 www 和 www http 请求重定向到 https://www
【发布时间】:2015-04-20 13:18:33
【问题描述】:

我需要将我网站上的所有非 www 请求和 http 请求重定向到 https://www.example.com。 我使用 Apache 服务器,但找不到任何有用的东西来帮助我做到这一点。 目前我使用 .htaccess 文件将非 www 请求重定向到 www。

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

【问题讨论】:

    标签: php apache .htaccess redirect https


    【解决方案1】:

    将此添加到您的 .htaccess 中:

    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    

    【讨论】:

    • 这可能是您的应用程序或服务器配置中的某些内容导致重定向。
    【解决方案2】:

    您可以使用这条规则来添加两个重定向:

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L,NE]
    

    【讨论】:

    • 你应该提到有问题的CloudFlare
    【解决方案3】:

    解决了! 我正在使用 CloudFlare CDN,所以我需要添加此代码来重定向非 https 请求。

    RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
    RewriteRule ^(.*)$ https://www.example.com/$1 [L, R=301]
    

    【讨论】:

      【解决方案4】:

      我们也可以通过 PHP 来实现,请查看以下代码:-

      if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == ""){
          $redirect = "https://".str_replace("www.","",$_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI'];
          header("HTTP/1.1 301 Moved Permanently");
          header("Location: $redirect"); } 
      
      $protocol = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://"; if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
          header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST']);
          exit; }
      

      【讨论】:

        猜你喜欢
        • 2018-09-26
        • 1970-01-01
        • 1970-01-01
        • 2015-05-01
        • 2012-05-30
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多