PHP 将代码 HTTP 重定向到 HTTPS


php redirecting code http to https

我想将我的 www.mysite.in 重定向到 https://www.mysite.in,我在索引中尝试了所有可能的 php 代码.php如下所述,但仍然无法重定向....我没有得到确切的解决方案。请帮助我。

<?php
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != '') {
    header("location: https://".$_SERVER['HTTP_HOST']);
} else {
    header("location: http://".$_SERVER['HTTP_HOST'])
}?>
------------------------------------OR---------------------------------------
<?php
if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == ""){
    $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: $redirect");
}
?>
------------------------------------OR----------------------------------------
<?php
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "")
    {
        $HTTPURI = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        header("HTTP/1.1 301 Moved Permanently"); // Optional.
        header("Location: $HTTPURI"); 
        exit(0);
    }
?>

像这样怎么样:

有一个功能可以检查网站的协议:

function is_https() {
    if (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 1) {
        return TRUE;
    } elseif (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') {
        return TRUE;
    } else {
        return FALSE;
    }
}

如果没有,则执行重定向。

if (! is_https()) {
    header("location: https://{$_SERVER['HTTP_HOST']}");
}

更好的是,您可以将.htaccess与以下代码一起使用。无需在每个页面中放置手动 php 代码,您可以控制整个网站的一个文件。

# Switch rewrite engine on
RewriteEngine on
# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www'.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
# Do index.php to root redirect
RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ https://%{HTTP_HOST}/$1 [R=301,L]