How to Force HTTPS Using .htaccess (Updated 2022)
After installing an SSL certificate, your website is available over HTTP and HTTPS. However, it’s better to use only the latter because it encrypts and secures your website’s data. While Hostinger allows users to configure this setting in just one click, you can also use the .htaccess file to force HTTPS connection. This tutorial will show you how.
Forcing HTTPS on All Traffic
One of the many functions you can perform via .htaccess is the 301 redirects, which permanently redirects an old URL to a new one. You can activate the feature to force HTTPS on all incoming traffic by following these steps:
- Go to File Manager in your hosting panel and open .htaccess inside the public_html folder. If you can’t locate it, make sure to create or unhide it.
- Scroll down to find RewriteEngine On and insert the following lines of code below it:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] - Save the changes.
Force www or non-www in your .htaccess file in cPanel
- First, log into your cPanel.
- Once logged into cPanel, Find the Files category and click on the File Manager icon.
- Next, click Settings at the top right corner.
- In the Settings Menu, choose the document root (or folder) for the domain you are working with and be sure the checkbox next to Show Hidden Files is checked. Click the Save button.
- Look for the .htaccess file and right click on it. This brings up a menu. Find and click on the Edit option.
- You are now in the text editor. Place either selection of code in the file and click on the Save Changes button at the top right corner of the screen. Be sure to replace ‘example.com‘ with your actual domain name.
NOTE: do not place both selections of code in the file as it will cause an error. Below are examples of code that you can use to implement the desired change to the website.
NOTE: do not place both selections of code in the file as it will cause an error. Below are examples of code that you can use to implement the desired change to the website.
Force www
#Force www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
Force non-www
#Force non-www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
No comments:
Post a Comment