簡體   English   中英

將非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; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM