How To Redirect HTTP to HTTPS using .htaccess file

Last updated on September 21st, 2021 at 10:42 am

When you add SSL to your websites, your web server will also continue to serve the HTTP version of your webpages. So you need to redirect HTTP to HTTPS, and force SSL on your website. Here’s how to redirect HTTP to HTTPs using .htaccess file in Apache web server.

 

How To Redirect HTTP to HTTPS using .htaccess file

Here’s how to redirect HTTP to HTTPS in Apache using .htaccess file. Please ensure that you have enabled mod_rewrite in your Apache server before you follow these steps. Only then the configuration in .htaccess file will be applied by your Apache server. After you migrate your website from HTTP to HTTPS, you may want to use a database reporting software to monitor key metrics about your website/application such as signups, purchases, revenue, etc. using dashboards & charts, to ensure that everything is working as before, and spot issues early.

 

1. Open .htaccess file

You will typically find .htaccess file in your site’s root folder (e.g /var/www/html/). You can open it using vi editor

$ sudo vim /var/www/html/.htaccess

 

2. Add Rewrite Rule to .htaccess

Add the following rules to your .htaccess file, to redirect HTTP to HTTPs

RewriteEngine on

# force ssl
RewriteCond     %{SERVER_PORT} ^80$
RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

The above rewrite condition checks if the requested port is 80 (default for HTTP). If so, it will match the whole URL and redirect to its HTTPS version. SERVER_NAME is the server variable for website’s root URL, and REQUEST_URI is the URL stub that follows the domain name. Here we use a 301 redirect, that is, a permanent redirect. If you don’t want a permanent redirect then simply use ‘R’ instead of ‘R=301’ in the above RewriteRule.

 

If you use virtual hosts, you can also redirect HTTP to HTTPS in your virtual host’s config file.

<VirtualHost *:80>
   ServerName www.example.com
   Redirect permanent / https://www.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName www.example.com
   DocumentRoot /var/www/html/example
   SSLEngine On
# etc...
</VirtualHost>

In above case, we set up 2 virtual hosts – one for HTTP and the other for HTTPS. The HTTP virtual host simply redirects all its requests to the HTTPs one.

You can also use URL redirection to redirect to subfolder or redirect subfolder to subdomain.

 

3. Restart Apache Server

Restart Apache Server to apply changes

$ sudo service apache2 restart

 

That’s it! Now your website will automatically redirect all HTTP requests to HTTPs ones.

By the way, if you want to create dashboards & charts to monitor your business or website, you can try Ubiq. We offer a 14-day free trial!