![Http to https , secure site](https://ipfail.org/wp-content/uploads/2020/12/http_1608174029.png)
1). How to redirect HTTP to HTTPS from .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
The above code redirects any subdomain not just the base domain. A 301 redirect is a permanent redirect that tell search engines that URL has moved permanently.
2). How to Redirect With PHP
if (empty($_SERVER['HTTPS'])) { header("HTTP/1.1 301 Moved Permanently"); $url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; header('Location: '.$url); exit; }
and some extended variant, to avoid multiple redirection if ssl is not working on server:
if ( (! empty($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] != 'https') || (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'on') || (! empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != '443') ) { $url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $query = parse_url($url, PHP_URL_QUERY); $rssl = true; if ($query) { $pos = strpos($query, 'rssl=1'); if ($pos === false) $url .= '&rssl=1'; else $rssl=false; } else $url .= '?rssl=1'; if ($rssl) { header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$url); exit; } }
3). Using a HTML meta tag, redirect only to homepage
meta http-equiv="Refresh" content="0;URL=https://yourdomain.com"
mixing with php and redirect any links
<?php if (empty($_SERVER['HTTPS'])) : ?> <meta http-equiv="Refresh" content="0;URL="https://<?php echo $_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];?>" > <?php endif; ?>
4). Automatic HTTPS JavaScript Redirect
if (location.protocol !== 'https:') { location.replace('https:${location.href.substring(location.protocol.length)}'); }
or
if window.location.href.match('http:') window.location.href = window.location.href.replace('http', 'https')
or
if (location.protocol !== "https:") { location.protocol = "https:"; }
The most common and secure are redirection from htaccess or php, but you must keep in mind that it is necessary for SSL to be functional, otherwise you can create multiple redirects and lose visitors!
Leave a Reply
Your email address will not be published. Required fields are marked *