How to force HTTPS using the .htaccess file

Occasionally you may need to force all traffic on your website to use HTTPS.  This can be accomplished by leveraging the Apache feature "mod_rewrite" in an .htaccess file.

Important: If you have existing code in an .htaccess file, place the following code above where there are similar rules with the Rewrite prefix

Forcing all traffic to HTTPS
To force all traffic to use HTTPS insert the following code into a file named ".htaccess" (without double quotes) into the website's root folder.  Be sure to replace the example domain with your own.
RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$$1 [R,L]

Forcing a specific domain to HTTPS
To force a specific domain to HTTPS, use the following code instead, again in a .htaccess file in your website's root.  Be sure to replace the example domain with your own.
RewriteEngine On 
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$$1 [R,L]

Forcing a specific folder to HTTPS
If you'd like to force HTTPS on a specific folder, you may use this code.   Place this in an .htaccess file in the folder you'd like HTTPS enabled upon.  Be sure to change the example domain as well as the correct folder name.
RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{REQUEST_URI} folder 
RewriteRule ^(.*)$$1 [R,L]

Was this answer helpful?

 Print this Article

Also Read

LinuxPro Hosting & SSL Certificates

Overview This document explains the Transport Layer Security (TLS) and Secure Sockets Layer...

Checking Your Outgoing Mail Server (Is port 25 blocked?)

INTRODUCTION Many email clients and services use port 25 for SMTP to send out emails. However an...

Is WHOIS Privacy Available?

WHOIS is a global database which stores some personal information of the person or entity...

PHP mail() function on LinuxPro Hosting

OverviewAs of June 2015, TLFHosting disabled the legacy PHP mail() function for all TLFHosting...

Does TLF back up my website's files?

The Linux Fix performs file-level backups on all our customer-facing servers free of charge....