2

I would like to push my logged in users to HTTPS but let non-logged in users remain on HTTP (the https is already set up). I took this code snippet from another SO post (apologies that I cannot now find the post to reference) and nested it within an if($loggedin) condition so that non-logged in users would not have to use https. All my paths are relative on the site.

if($loggedin)
    {
    if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
        if(!headers_sent()) {
            header("Status: 301 Moved Permanently");
            header(sprintf(
                'Location: https://%s%s',
                $_SERVER['HTTP_HOST'],
                $_SERVER['REQUEST_URI']
            ));
            exit();
        }
    }
}

I tried putting in some javascript alerts within the function, but when I load the page I never see the alerts and instead go right to the redirect error message. I don't know if it's relevant, but I am running this with elastic load balancing with apache server on AWS.

Any ideas as to what I could be doing wrong here? Or tips for trouble-shooting since my javascript alerts did not show up? Thank you.

Edit: I found the SO post I originally took this code from: Force SSL/https using .htaccess and mod_rewrite

Community
  • 1
  • 1
Cauchy Kun
  • 177
  • 2
  • 11
  • Does it work if you leave out the `Status` header? I've never used that when sending a redirect. – Barmar Jan 10 '15 at 00:06
  • do you using .htaccess file? if yes please send details – phpniki Jan 10 '15 at 00:15
  • @phpniki I am not using a .htaccess file. Just searched my server and did not find any version of an .htaccess file. – Cauchy Kun Jan 10 '15 at 00:21
  • @Barmar sorry for the lag, takes a while to reload server with elastic load balancing. I deleted the line header("Status: 301 Moved Permanently");, but I still have the same error. – Cauchy Kun Jan 10 '15 at 00:22
  • there is not enough information about your current situation and current debug info. so does your `header('Location` work? do you see changes in browser address line? if not then just put some echo in `else` section for each `if` that you have not now, just for better understanding what is missing – Alex Jan 10 '15 at 02:42

1 Answers1

0

There isn't enough information in your question, but you mention that you're using a load balancer in one of your comments.

If you are terminating SSL on the load balancer, but using HTTP between the ELB and your instance, then this check will always fail:

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {

Instead, you will need to check X-Forwarded-Proto to see if the original request is HTTPS.

chris
  • 36,094
  • 53
  • 157
  • 237
  • You were exactly right. It was my server referring back to ELB referring back to myserver as a result of not checking X-Forwarded-Proto. – Cauchy Kun Jan 11 '15 at 17:54