How To Redirect HTTP to HTTPS using .htaccess file (Apache Server)

When you are adding SSL for your websites to make it’s secure, your web server will also continue to serve the HTTP version of your webpages. So to get Website Visitor/your audiences’ attraction, you need to redirect HTTP to HTTPS, and force SSL on your website. Here’s I am giving some examples “how to redirect HTTP to HTTPs using .htaccess file in Apache web server”.

Steps to Redirect HTTP To HTTPS Using .Htaccess File

Before you start the things-Kindly ensure you have mod_rewrite enabled in your Apache server. Then only your Apache server will apply the configuration in .htaccess file. After migrating your website from HTTP to HTTPS, you may need to use a database reporting software for monitoring the key metrics about your website/application like signups, purchases, revenue, etc. with the help of dashboards & charts, to make sure everything is working smoothly and issues are spotted early.

Open .htaccess file

You will usually find .htaccess file in the root folder (e.g /var/www/html/) of your site. You can open it with the help of code editor

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

Add Rewrite Rule to .htaccess

Add the below mentioned rules to your .htaccess file, for redirecting HTTP to HTTPs

RewriteEngine on

# force ssl

RewriteCond %{SERVER_PORT} ^80$

RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

If the requested port is 80 (default for HTTP) then the above rewrite condition will check. In that case, it will match the entire URL and redirect to its HTTPS version. The server variable for website’s root URL is SERVER_NAME, and the URL stub that follows the domain name is REQUEST_URI. For permanent redirect here we use a 301 redirect. If you don’t need a permanent redirect then just use ‘R’ instead of ‘R=301’ in the above RewriteRule.

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

<VirtualHost *:80>


Redirect permanent /



<VirtualHost _default_:443>


DocumentRoot /var/www/html/example

SSLEngine On

# etc…



In above mentioned case, we want to set up 2 virtual hosts – one for HTTP and the other one for HTTPS. The HTTP virtual host easily redirects all its requests to the HTTPs one. You can even use URL redirection to redirect to subfolder or redirect subfolder to subdomain.

Restart Apache Server

Restart Apache Server to apply changes

$ sudo service apache2 restart


For more guidance contact experts!

Share this post