EZ SERVICES
EZ SERVICES

Reputation: 113

How to Redirect one page to HTTPS in PHP?

I am trying to redirect only the index page of my website to HTTPS version using the following code but it gives domain.com redirected you too many times i.e ERR_TOO_MANY_REDIRECTS error. There are no redirect codes in htaccess except the 4XX & 5XX error redirections.

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

How to redirect only one page to HTTPS without affecting other URLs in PHP?

Upvotes: 1

Views: 128

Answers (2)

Keith Tysinger
Keith Tysinger

Reputation: 251

Here is my code for doing redirect for non www pages. You can adapt it easily for https.

// redirect to www if necessary
$kc_ur_pos = stripos($_SERVER['HTTP_HOST'],'www.');

if ($kc_ur_pos === false) 
{ $kc_ur='https://www.';
$kc_ur .= $_SERVER['HTTP_HOST'];
    $HTTPURI = $kc_ur . $_SERVER['REQUEST_URI'];
    header("HTTP/1.1 301 Moved Permanently"); // Optional.
    header("Location: $HTTPURI");
    exit;}

Upvotes: 0

Machavity
Machavity

Reputation: 31654

Your problem is in this line

if($_SERVER['HTTPS'] !== "on")

Per the manual

'HTTPS' : Set to a non-empty value if the script was queried through the HTTPS protocol.

So just use

if(!$_SERVER['HTTPS'])

Upvotes: 1

Related Questions