How to redirect www to non-www and HTTP to HTTPS in Apache using .htaccess

Did you notice that some website’s names start with or without WWW? This creates a duplicate content issue on google and also impacts our website SEO.

Search engines see and as two different websites with the same content. This causes them to see a lot of duplicate content, which they don’t like and most of the time does not allow website pages to rank in google.

When your website is not directing traffic to and to the same URL. It is crucial that you fix this. Use the rel=”canonical” tag to tell google search engines which one is the main version of the website. Use .htaccess file to redirect all page versions to main.


Here we will show you how to redirect a website from www to non-www and from HTTP to HTTPS, using the .htaccess file in Apache server. The following are the steps below.


Apache Configuration (.htaccess file)

Add the following code in your .htaccess  file, which you can get at the root of the website. If it is not visible in FTP then try to login to your server and go into the website root folder. Still, if you are unable to find hidden files (.htaccess) there then visits How to enable or disable the hidden (.htaccess) files in cPanel. Dotfiles are considered hidden files in Cpanel

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

If instead of if you need the default URL to be, then simply change the third and the fifth lines:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]