Apache – Redirect HTTP requests to HTTPS
This post shows you three approaches how to redirect all insecure HTTP requests on a site to secure HTTPS.
1. Using .httaccess approach
.htaccess
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
2. Using server configuration file approach
<VirtualHost *:80>
ServerName www.example.com
Redirect "/" "https://www.example.com/"
</VirtualHost>
<VirtualHost *:443>
ServerName www.example.com
# ... SSL configuration goes here
</VirtualHost>
You can find more information about this approach here.
3. Using PHP approach
redirect-to-https.php
<?php
function redirectToHttps()
{
if ($_SERVER['HTTPS'] !== 'on') {
$httpsUrl = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: $httpsUrl");
}
}
With this simple PHP approach, you simply call that redirectToHttps()
function in your PHP application.