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

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 www.abc.com and abc.com 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 www.abc.com and abc.com 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.

Introduction

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.

http://abc.com
http://www.abc.com
https://abc.com

to

https://abc.com

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 abc.com if you need the default URL to be www.abc.com, 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]

Spread the love