No Results Found
No Results Found

Reputation: 102735

Forcing http/https: How to detect https and which status header to send when redirecting?

I've written a script to force certain sections of the site to be accessed via http or https. We want the user to be redirected to the normal http page in case they land on the https version by accident, and vice versa. So far, so good, but I have 2 questions for you guys.

  1. What is the correct status header to send when switching protocol? I'm currently using this in both cases before redirecting:

    header('HTTP/1.1 301 Moved Permanently');
    
  2. What is the preferred way to detect if we're using https?

    // if ($_SERVER['SERVER_PORT'] == 443) /* EDIT: OK, not this? */
    
    if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on'))
    

    Something else? Both?

Replies to comments:

Upvotes: 2

Views: 1899

Answers (1)

Marcus Adams
Marcus Adams

Reputation: 53830

  1. The 301 redirect is the proper method. You cannot switch between HTTP and HTTPS mid-stream. The page must be reloaded in the client.
  2. The second method, via $_SERVER['HTTPS'] is the preferred method. Simply ensure that your web server supports it.

Upvotes: 3

Related Questions