将非 www 和 www 的 http 请求重定向到 https://www

Redirect non-www and www http requests to https://www

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

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

将此添加到您的 .htaccess:

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

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

RewriteEngine On

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

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

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

我们也可以通过 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; }