301 Redirect : http to https and www to non-www


http to https and www to non-www  301 Redirect using .htaccess file

301 Redirect: Suppose, you have a website like http://sitename.com and you want to get a secured server layer(SSL) to your website for better security purpose and planned to move your whole site (included all pages and images) to https://sitename.com  with www or non-www. Securing your website has become an essential steps to ensure services to your customers continuously and confidently. Customers usually feel more secure when they found that a site has a secure seal on front of the webpage address.

There are also paid and free SSL Certificate available on the net. The paid SSL Certificate is bit costly. If you have a good budget for your site improvement, then go for paid SSL Certificate. There are some good free SSL Certificate services also. I have installed Let’s Encrypt SSL certificates on some of my websites. It is very much easy to setup on Cpanel.Please visit the site and read the instructions and apply accordingly.

Here I am showing how you can redirect a website from www to non-www (vice-versa) and http to https using the Apache server configuration and 301 Redirect.  For More Illustration and clarification, the below configuration on the Apache Server will redirect the following domain names.

http://sitename.com

http://www.sitename.com

https://sitename.com

To

https://sitename.com

If you prefer the www version, I will show a little change to redirect the non-www to www version.

Apache Configuration

If you have a permission to Apache config file, just add the following redirect codes or to .htaccess in the root of your website.If RewriteEngine On already attached on your .htaccess file than ignore the first line.

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 you want default URL to be www.sitename.com instead of sitename.com than change the fifth line

 

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]

Note : an extra RewriteCond line (stated earlier) to extract the host name, and avoid to inline the hostname in the rule. If you want you can inline the host directly in the rule:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www. [NC]
RewriteRule ^ https://sitename.com%{REQUEST_URI} [L,NE,R=301]

Conclusion: It is a simple configuration to redirect www and non-HTTPS request to the canonical domain using 301 Redirect. It is very much useful to avoid content duplication issues with search engines.Hope users will be benefit from this article.

©Shubho Salateen-2018

Like on Facebook