Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php redirecting code http to https

Tags:

redirect

php

I want to redirect my www.mysite.in to https://www.mysite.in, I tried all possible code of php in index.php as below mentioned but still unable to redirect....I am not getting exact solution. Please help me regarding.

<?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);
    }
?>
like image 937
Vijaya Savant Avatar asked Mar 14 '15 05:03

Vijaya Savant


2 Answers

How about like this:

Have a function that will check the protocol of the website:

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

Then if not, you do the redirect.

if (! is_https()) {
    header("location: https://{$_SERVER['HTTP_HOST']}");
}
like image 167
Vainglory07 Avatar answered Oct 01 '22 12:10

Vainglory07


Better you can use .htaccess with the below code. Instead of putting manual php code in each page you can control one file the whole website.

# 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]
like image 27
Vetrivel Avatar answered Oct 01 '22 14:10

Vetrivel