Enforcing visitors to HTTPS


#1

I just encrypted my website, and everything works well. Except that when you enter the domain as “domain.com” or “www.domain.com”, the line will not be secure, until you actually click a link on the website that directs you to a secure page. This is annoying. So I decided that I wanted to use PHP to enforce HTTPS into the URL. I have tried two methods:

Method 1:

[php]if (!isset($_SERVER[‘HTTPS’]) || !$_SERVER[‘HTTPS’]) { // if request is not secure, redirect to secure url
$url = ‘https://’ . $_SERVER[‘HTTP_HOST’]
. $_SERVER[‘REQUEST_URI’];

header('Location: ' . $url);
exit;

}

[/php]

Method 2:
[php]
if(empty($_SERVER[“HTTPS”]) || $_SERVER[“HTTPS”] !== “on”)
{
header(“Location: https://” . $_SERVER[“HTTP_HOST”] . $_SERVER[“REQUEST_URI”]);

}

[/php]
Both give the same error:
Warning: Cannot modify header information - headers already sent by (output started at domain.com/connection.php:1) in domain.com/connection.php on line 5.

The troublesome line would then be the header, which is the last line in both approaches. What can I do about it?

When I type echo instead of header to print out the URL, the URL seems to be right, so I don’t understand why the user isn’t redirected.


#2

You are looking at the wrong thing. You want to make an .htaccess rule that does this for you.


#3

Create a .htaccess file and put it in your root folder :

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

Be sure to replace www.example.com with your actual domain name.