Redirect non-www to www & HTTP to HTTPS using .htaccess file

The use of .htaccess file is to override the main server configuration. .htaccess file placed in a directory. Therefore, it applies the configuration to that particular directory and all the subdirectories. It is mostly used in Rewriting URLs, Blocking, SSL, Customized error responses, Directory listing, Cache-Control, etc.

With the help of this following tutorial will explain to you the most used URL redirection process through the .htaccess file. Firstly, you’ll see how to redirect non-www URLs to www. Secondly, we will show you how to redirect HTTP to HTTPS using .htaccess file.

Creating .htaccess File

Make a file with .htaccess extension in the root directory of the website domain. It can be a simple text file. Therefore, you can edit this file with any text editor.

SEE ALSO: Build an HTML5 Video Player with Custom Controls

Redirect non-www to www

According to the Search Engine prospect, non-www and www URLs are different aspects. So, it can affect site SEO. For example, http://allseweb.com and http://www.allsweb.com are technically different, and when Search Engine fetching the same content from different URLs, treat it as a duplicate content. So, it will be a good idea if you redirect all requests (non-www) to the same URL format (www). Using this file, you can redirect non-www to www URLs.

Add the following code in the root .htaccess file.

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

SEE ALSO: Create a Digital Clock with Date using JavaScript

Redirect HTTP to HTTPS

If you already have the secure certificate (SSL) on your website, you could redirect visitors to the stable web version. Sometimes SSL encrypted connection is necessary for your website’s visitors. So, it would be best if you forced the visitors to use SSL by automatically redirect HTTP to HTTPS version URL. Also, it is okay if all the URL request is redirected to the HTTPS and www formatted URL.

Add the following code.

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.mysite.com/$1 [R,L]

Note: Please do not forget to replace mysite.com with your site’s domain name.

Also, read our previous blog- Confirmation Before Closing of Tab/Browser using JavaScript

Exit mobile version