HTTP redirection to HTTPS in Apache

By Darío Rivera
Posted On in Apache

Once you have successfully installed an SSL certificate on your website, you want all current traffic over HTTP to be redirected to HTTPS. With Apache, this task is fairly simple and can be done in two main ways, which we will see below.

Before continuing with this post, we recommend that you read our latest article

SSL Certificate with Let's Encrypt

In it, you will learn how to install an SSL certificate for your website for free and quickly. That being said, let's take a look at the two main ways we can redirect HTTP traffic to HTTPS.

From the domain configuration file

When you configured your domain with Apache, you most likely created a .conf configuration file in sites-available or another location on your server. This file is different from the SSL configuration, which should be separated into a different file. So let's modify the .conf file of your domain and add a permanent redirection to your HTTPS version like this:


# HTTP to HTTPS redirection
Redirect permanent /

The Redirect permanent directive sends all traffic to our HTTPS version of the site with an HTTP 301 code. This is quite convenient according to SEO recommendations.

From the .htaccess file of your site

Another way to perform the same redirection is to add the directives in the .htaccess configuration file of the website like this:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Note that the R=301 rule ensures that the redirection is done by sending an HTTP 301 - Moved Permanently code, just like in the previous example.

Verify your website's redirects

As an additional point, you should verify that your website's redirects are functioning correctly. In this post, we will assume that redirects to and of course the flow over http redirects to https. You can verify this with curl if you get an HTTP 301 - Moved Permanently.

$ curl -I
HTTP/1.1 301 Moved Permanently
Date: Sun, 24 May 2020 16:41:43 GMT
Server: Apache/2.4.38 (Debian)
Content-Type: text/html; charset=iso-8859-1
$ curl -I
HTTP/1.1 301 Moved Permanently
Date: Sun, 24 May 2020 16:42:09 GMT
Server: Apache/2.4.38 (Debian)
Content-Type: text/html; charset=iso-8859-1

Note that the location is the URL where the traffic was redirected.

Acerca de Darío Rivera


Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.