How to create a redirect in .htaccess

keyboard_arrow_down

This guide explains how to create an .htaccess file.

Chrome and Firefox have recently started showing insecure warnings on sites without SSL certificates. Without SSL, your website will display an insecure warning to visitors.

It is therefore necessary to use an SSL certificate for security, accessibility or PCI compliance reasons. It is therefore very important to force your website from HTTP to HTTPS.

What is SSL?

SSL (Secure Sockets Layer) is a standard security protocol for establishing encrypted connections between a web server and a browser.

The use of SSL technology ensures that all data sent between the web server and the browser remains encrypted.

An SSL certificate is required to establish an SSL connection. You must provide full details about the identity of your website and/or company when you choose to activate SSL on your web server. After this, two cryptographic keys are created: a private key and a public key.

To force your visitors to HTTPS, edit the code in the .htaccess file.

Before we move on to redirecting HTTP to HTTPS, here’s how to edit the .htaccess file.

edit .htaccess file

An .htaccess file provides instructions/directives that tell the server how to act in certain scenarios and directly affect how your website functions.

General guidelines in .htaccess file:

  • Redirects
  • Rewrite URLs

Ways to edit a .htaccess file:

  1. Edit the file on your computer and upload it to the server via FTP.
  2. Use the “Edit” mode in the FTP program that allows you to edit a file remotely.
  3. Use a text editor and SSH to edit the file.
  4. Use the File Manager in cPanel or DirectAdmin to edit the file.

Redirecting HTTP to HTTPS

1. Redirect all web traffic
If you have existing code in your .htaccess add the following:


RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]

2. Redirect only a specific domain

Add the following code to redirect a specific domain and use HTTPS:


RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]

3. Redirect only a specific folder

To redirect to HTTPS on a specific folder, add the following code:


RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ https://www.yourdomain.com/folder/$1 [R,L]

Note: Replace “yourdomain” with your actual domain name where necessary. In the case of the folder, also replace /folder with the actual folder name.