1

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?

EZ SERVICES
  • 113
  • 2
  • 16
  • 1
    Check `$_SERVER['HTTPS']`, is it really `on`? – u_mulder Jan 10 '17 at 13:29
  • How is the SSL/HTTPS certifcation being handled? For instance, if you are behind a proxy that is handling the SSL then the above will indeed result in a redirect loop. But there are alternative checks you can make if this is the case. – MrWhite Jan 12 '17 at 08:27

2 Answers2

1

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'])
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • Too bad there's IIS to not follow the guidelines and set HTTPS to off when there's no HTTPS – apokryfos Jan 10 '17 at 13:30
  • @apokryfos I think that only applies with the ISAPI plugin. If you're using it in FCGI (much more common) I don't think that applies – Machavity Jan 10 '17 at 13:33
  • 1
    per http://stackoverflow.com/a/7304205/1415724 `if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')` - so, that's kind of the opposite of what they're trying to do now, to which I found quite a few questions that include `($_SERVER['HTTPS'] !== "on")`, just saying. One being http://stackoverflow.com/q/1175096/1415724 and http://stackoverflow.com/a/19949133/1415724 – Funk Forty Niner Jan 10 '17 at 13:33
0

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;}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Keith Tysinger
  • 251
  • 2
  • 5
  • Sorry, this doesn't answer the question. The important part of this question is the condition on which this redirect should be triggered, and that part is not even addressed. – MrWhite Jan 10 '17 at 16:59