How to force HTTPS using JavaScript ?
You can use location.protocol in JavaScript to detect the protocol of current URL and then use location.replace property to redirect the current URL to HTTPS page.
JavaScript Code to force HTTPs usage.
<script type="text/javascript">
if (location.protocol !== 'https:') {
location.replace(`https:${location.href.substring(location.protocol.length)}`);
}
</script>
PHP script to redirect/force HTTP to HTTPS
<?php
if(!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on")
{
$https_url= "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]";
header("Location: ". $https_url.", true, 301);
exit();
}
?>
Forcing HTTPS using .htaccess
Copy and paste this code to redirect HTTP to HTTPS in Apache web server
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}