I wrote this recently, I thought I'd check if it was the best way to keep my url as an https at all times, any advice would be appreciated

   if($_SERVER["HTTPS"] != "on")
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
  • \$\begingroup\$ I just use HTACCESS, this way it doesn't "infect" my code on my local test machine (I don't transfer .htaccess ). I could use HTTPs on that (local), but I'm to lazy to set up the keys :-p \$\endgroup\$ – ArtisticPhoenix Aug 23 '18 at 3:49

If the request is already being served over HTTPS, then it would be a good idea to add a Strict-Transport-Security header to the response. Strict-Transport-Security tells the browser that, as a matter of policy, your site wants all requests to your domain to be made over HTTPS.

Be aware that redirecting an HTTP POST request would cause the browser to make an HTTP GET request. To cause the second request to also be made as a POST, you would need to respond with a a 307 status code. Of course, the benefit of a 307 redirect of a POST is questionable, as any sensitive POST data will have already been transmitted unencrypted already.

  • \$\begingroup\$ Thank you, seems like a lot of good information to go over \$\endgroup\$ – confusedGibbon Aug 19 '18 at 23:18

Documentation on HTTPS key says that it indicates the protocol was used when its value is not empty and is not equal to 'off' (used on on IIS) - correct condition for it would be

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') { ... }

It doesn't look like a library, but you might want to handle request port value from SERVER_PORT key. Default port (443 for https/80 for http) should be omitted.


In addition to the points already raised:

The documentation of header says

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

So it's worth asking whether 302 is the most appropriate response code in this case, and I suspect that it would be better to return 301 (Moved Permanently).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.