HTTPS & WWW Redirection for Apache HTTP Server

By XaHertz  |  January 12, 2023  |  Last Updated : November 6, 2024

Developers and system administrators now face a few new challenges as HTTPS becomes more widely used as the standard connection protocol for websites. One of these challenges is the requirement to consolidate a canonical domain by rerouting non-HTTP sites to HTTPS in addition to rerouting non-www to www host names (or vice-versa).

For that purpose adding the following code into your website's .htaccess configuration file will make it Rediect to the HTTPS and WWW version of the website. An .htaccess file is a configuration file used by Apache-based web servers to specify how web requests should be handled. It is placed in a specific document directory and contains one or more configuration directives that apply to that directory and all of its subdirectories. It enables you to make changes to the configuration of your website without having to edit server configuration files. You can use it to restrict website access, redirect URLs, create custom error pages, and much more. You can create an .htaccess file using a text editor such as Notepad or Visual Studio Code. Here are the steps to create it:

  • Open your text editor.
  • Create a new file.
  • Save the file as .htaccess.
  • Upload the file to your website’s root directory.

Once you have created the .htaccess file, you can add the following configuration to it to make it Rediect to the HTTPS and WWW version of the website. Replace example.com with your websites domain name. For non-www redirection replace example.com with www.example.com in 4th line and www.example.com with example.com in 5th line.

## BEGIN WWW Redirection ##
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
</IfModule>
## END WWW Redirection ##

## BEGIN HTTPS Redirection ##
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]  
</IfModule>
## END HTTPS Redirection ##

To see if the Redirect works, enter your domain name without the www in the address bar of your browser. It is working if it redirects to your domain name with www. It doesn't work if it doesn't redirect or redirects to a different page. You can also use an online tool, such as Redirect Checker, to determine whether your Apache Redirect is working properly.

I hope this article was helpful and saved you some hassle. Thanks For Reading!


Last updated on November 6, 2024