Redirecting from HTTP to HTTPS with PHP on IIS
I was having trouble getting redirection to HTTPS to work on a Windows server
which runs version 6 of MS Internet Information Services (IIS). I’m more
used to working with Apache on a Linux host so I turned to the Internet for
help and this was the highest ranking Stack Overflow question when I searched
for “php redirect http to https”. However, the selected answer didn’t work
for me.
After some trial and error, I discovered that with IIS, $_SERVER['HTTPS']
is
set to off
for non-TLS connections. I thought the following code should
help any other IIS users who come to this question via search engine.
<?php
if (! isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off' ) {
$redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $redirect_url");
exit();
}
?>
Edit: From another Stack Overflow answer,
a simpler solution is to check if($_SERVER["HTTPS"] != "on")
.