Force SSL Certificate/HTTPS using .htaccess

Have you ever had an issue hosting a website with SSL installed and it still appears to show not secured?

Same here, it was a nightmare to me until I had it sorted out using .htaccess

What is .htaccess?

.htaccess (hypertext access) file is a directory-level configuration file supported by several web servers, used for configuration of website-access issues, such as URL redirection, URL shortening, access control (for different web pages and files), and more. The ‘dot’ (period or full stop) before the file name makes it a hidden file in Unix-based environments.

For WordPress users, it’s usually installed during your WordPress installation, and if you’re developing from scratch you need to manually add the .htaccess. Where to find or add a .htaccess file.

  1. Go to File Manager in your cPanel and open .htaccess inside the public_html folder. If you can’t locate it, while you’re still on the File Manager click on Settings on the top right corner, and check the Show Hidden Files (dotfiles), and save.
Settings on the top right corner.
Show Hidden Files (dotfiles).

2. If the file does not exist in the file manager create a new file with the title .htaccess the copy and paste the code below and then save, but if the file already exists in the file manager copy and paste the code below and save.

For some hosting platforms, this is to validate that the files uploaded on the server are clean which will trigger the SSL/HTTPS.

Header set Content-Security-Policy: upgrade-insecure-requests env=HTTPS

While some hosting platforms the code will work.

RewriteEngine On 
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

3. Save the changes.

After making the changes, clear your browser’s cache and try to connect to your site via HTTP. If everything was added correctly, the browser will redirect you to the HTTPS version.

Conclusion

Congratulations! you have successfully edited your .htaccess file and redirected all HTTP traffic to HTTPS, the safe version of your website.

Visit: www.thankgodokoro.codes to see some cool stuff I have worked on.

🤓Nerd | Brand Strategist | Full Stack Developer | UI/UX Designer | Graphic Designer | Product Designer | Founder : @Webifyng