DEV Community

Dennis Hüttner
Dennis Hüttner

Posted on • Updated on

Force Https with .htaccess

After installing an SSL certificate, your website will be accessible via HTTP and HTTPS. However, it is better to use only the latter, because it encrypts and additionally secures the data of your website. With some hosters there is a setting in the web interface to force HTTPS with just one click. Unfortunately, it happens again and again that this setting does not work correctly with various CMS systems. You can also use the .htaccess file (which we recommend) to force an HTTPS connection. This tutorial shows you how to do that.

Force HTTPS for all traffic

One of the many options you have with .htaccess files is to redirect HTTP traffic to HTTPS. You can enable the feature to force HTTPS for all incoming traffic by following the steps below:

  1. Go to the file manager in your hosting panel and open the .htaccess in the appropriate folder where your domain points to. If the file is not there, you may need to create and/or share it.
  2. Scroll down until you find "RewriteEngine On" and paste the following lines of code below it:
RewriteEngine On 
RewriteCond %{HTTPS} off 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Enter fullscreen mode Exit fullscreen mode
  1. Save the change.

IMPORTANT: Make sure that the line "RewriteEngine On" does not appear twice. If the line already exists, simply copy the rest of the code without it.

Forcing HTTPS for a specific domain

If you have two domains that both point to the same website, but only the first domain should be redirected to https (for whatever reason), you can use the following code:

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^yourdomain-1.de [NC] 
RewriteCond %{HTTPS} off 
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Enter fullscreen mode Exit fullscreen mode

Force HTTPS for a specific folder

The .htaccess file can also be used to force HTTPS for specific folders. However, the file should be placed in the folder that is to establish the HTTPS connection.

RewriteEngine On 
RewriteCond %{HTTPS} off 
RewriteRule ^(folder1|folder2|folder3) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Enter fullscreen mode Exit fullscreen mode

Replace the "folder" with your "directory".

After you have made the changes, clear your browser's cache and try to connect to your website via HTTP. If everything was added correctly, it will now redirect to the HTTPS version.

Conclusion

Congratulations! You have just successfully edited your .htaccess file and redirected all HTTP traffic to the secure version HTTPS. Depending on the platform you developed your site on, there may be alternative methods to enable this feature.

If you have any tips, tricks, or suggestions to share with us, we welcome your comments!

Connect me on Twitter, LinkedIn and [GitHub]!

Visit my Blog for more articles like this.

Top comments (0)