How to Force HTTPS Through PHP or HTACCESS

HTTPS (Hyper Text Transfer Protocol Secure) is a secure encrypted version of HTTP (Hyper Text Transfer Protocol). It’s the protocol over which data is sent between your browser you are using and the website that you are browsing only. HTTPS sends all the sensitive data in an encrypted form whereas HTTP sends all the data in plain text. SSL uses a mathematical algorithm to hide the true meaning of the data. The algorithm is so complex that it is either impossible or prohibitively difficult to crack.

HTTPS is the basic price of security for the time. It’s the basic trust could you give to your visitors.

Read more – HTTP vs HTTPS. How Does HTTPS Work? Why Use SSL Encryption?

Now let’s go further and see how we can actually force HTTPS

How to Force HTTPS Through PHP – Method 1

Open your php web page files and put these codes on the top. You can even put the following codes in a common file like a header or a footer file which makes the task easier instead of putting the codes in every php page.

<?php if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
}  ?>

Now, HTTPS has now been forced on your website. Try opening your website using your favourite browser and you will see that HTTP version of your site will automatically redirect the visitors of your site to the HTTPS version.


How to Force HTTPS Through .HTACCESS – Method 2

Most of the web servers support reading of .htaccess file which is placed in the home directory of your website. However some web servers like Nginx don’t support reading of .htaccess file but you can still use a combination of Apache and Nginx as reverse proxy and make your website support reading of .htaccess file.

Put the following codes in the .htaccess file of your website to force HTTPS.  

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Header always set Strict-Transport-Security "max-age=31536000"

#for subdomains
<IfModule mod_headers.c>
Header set Strict-Transport-Security "max-age=10886400; includeSubDomains; preload" env=HTTPS

HTTPS will now be forced on every web page of your website. You may check it by opening your favourite browser and browsing your website. You will notice that if you browse the HTTP version of your site then you will be automatically redirected to the HTTPS version of your website.


yoast seo premium free