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”.

How To Redirect HTTP to HTTPS using .htaccess file

Before proceed the things-Please ensure that you have enabled mod_rewrite in your Apache server. 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 smooth, 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 code 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>
    Redirect permanent /

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

    In above case, we need to 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



Share this post