Set up your redirects in your .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}
[L,R=301]
</IfModule>
Look confusing? Here’s the breakdown:
- “RewriteEngine On” enables the rewrite
- “RewriteCond %{HTTPS} off” checks for the HTTP connection
- “RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUSEST_URI} [L,R=301]” redirects HTTP to HTTPS with a 301 status code
You can also solve this from within PHP in case your provider has disabled .htaccess (which is unlikely since you asked for it, but anyway)
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
if(!headers_sent()) {
header("Status: 301 Moved Permanently");
header(sprintf(
'Location: https://%s%s',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
));
exit();
}
}