HTTP forwarding https using php

I recently installed SSL for a domain. It's on shared hosting, which seems to be causing problems with site redirection to https

. I have asked previous questions regarding this issue with no success. It seems like any attempt is causing the site to go into an endless redirect loop. I was provided with the following code by a service providing site host that solves the redirection issue, but not in all browsers. In Chrome, the code works as intended, redirecting the page http

to its counterpart https

. However, tests in Internet Explorer seem to redirect all pages to the home page https

, and Firefox seems to just show an error screen. The code looks like this

 <?php 
 if ($_SERVER['HTTP_X_FORWARDED_SSL'] == '1') {      header("Location: $redirect");    } else {    $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];    header("Location: $redirect"); } ?> 

      

Can anyone describe this code to find a solution to this problem that has now been working for a long time.

+3


source to share


4 answers


I can't tell why it doesn't work, but try the code below to redirect http: // to https: //

if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == ""){
    $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    header("Location: $redirect");
}

      



This will work on every browser. Hope this helps you

+1


source


Use the following code:



<?php
if(isset($_SERVER['HTTPS'])) {
   $prefix = 'https://';
} else {
$prefix = 'http://';
}

$location = $prefix.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header("Location: $location");
exit;
}

?>

      

+1


source


I removed header("Location: $redirect");

the operator from the true command if

and the script now works in all browsers.

<?php 
 if ($_SERVER['HTTP_X_FORWARDED_SSL'] == '1') {  } else {    $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];  header("HTTP/1.1 301 Moved Permanently");  header("Location: $redirect"); } ?>

      

0


source


use this code

$protocol = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ) ? 'https' : 'http';

      

0


source







All Articles