Search Our Database

How to enforce SSL for website by editing `.htaccess` via SSH

Last updated on |
by

Introduction

This guide explains how to enforce SSL (HTTPS) on your website by editing the .htaccess file via SSH. The .htaccess file is a powerful configuration file used by the Apache web server to control various settings, such as URL redirects, access restrictions, and enabling or disabling certain server features. By leveraging .htaccess in combination with Apache’s mod_rewrite module, you can redirect all HTTP traffic to HTTPS, ensuring that all connections to your site are secure.

 

Prerequisites

Before proceeding, ensure you have:

  • SSH access to your web server.
  • A valid SSL certificate installed on your domain.
  • The mod_rewrite module enabled on your Apache server

.

Steps to enforce SSL for your website by editing “.htaccess”

1. Use an SSH client (such as PuTTY or Terminal) to log in to your web server

ssh root@<server_ip>

 

2. Locate the `.htaccess` file in the main directory of your web server. This file is typically found in the root folder of your website, in most control panel, it’s in public.html under home directory

cd /home/<user>/<website domain>/public.html/

If you do not have a control panel installed, your website root directory will typically be on /var/www/html

cd /var/www/html

 

3.If an .htaccess file already exists in the root directory, open it for editing. If it does not exist, you can create a new one.

vi .htaccess

 

4.If you wish to redirect all traffic to a HTTPS link, Add the following code to your .htaccess file to force all HTTP traffic to HTTPS:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ <URL>/$1 [R=301,L]

whereas:

<url> = Landing page for ssl redirection

*Note: The `.htaccess` file must be placed in the main folder of your web server.

 

If you wish to redirect only certain URL to a HTTPS link, use the following code snippet.

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{REQUEST_URI} <directory> 
RewriteRule ^(.*)$ <URL>/$1 [R,L]

whereas:

<url>           = Landing page for ssl redirection

<directory> =Root directory for the desired virtual host

*Note: Ensure the `.htaccess` file is located in the subdirectory of the page you want to secure.

 

5. save and close the file by pressing ESC, followed by “:wq”, if you are using vi editor

 

Conclusion

The .htaccess file is a versatile tool that allows you to manage various server-side behaviors without modifying the core server configuration. By enforcing SSL through .htaccess, you ensure that all visitors to your website are automatically redirected to the secure HTTPS version, enhancing both security and user trust.

Enforcing SSL is crucial for securing sensitive data and complying with modern web standards. If you experience any issues or need further assistance, please contact our support team at support@ipserverone.com.

 

 

Article posted on 4 April 2020 by ips1