将非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}/$1 [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/$1 [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; }