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

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

This HTACCESS tutorial will show you the most used URL redirection process through the .htaccess file. At First, you’ll see how to redirect non-www URLs to www and the second one will show you how to redirect HTTP to HTTPS using .htaccess file.


Creating .htaccess File

Create a file with .htaccess extension in the root directory of website domain. It would be a simple text file and you can edit this file with any text editor.

Redirect non-www to www

As per the Search Engine prospect, non-www and www URLs are different and it could affect site SEO. For example, and are technically different and when Search Engine fetching same content from different URLs, it is treated as duplicate contents. So, it will be a good idea if you redirect all requests (non-www) to the same URL format (www). Using .htaccess file, you can easily 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]

Redirect HTTP to HTTPS

If the secure certificate (SSL) was installed at your website, you can redirect visitors to the secure web version. Sometimes SSL encrypted connection is necessary for your website’s visitors. Means, you should be forcing visitors to use SSL by automatically redirect HTTP to HTTPS version URL. Also, it would be better if all the URL request is redirected to the HTTPS and www formatted URL.
Simply add the following code in the root .htaccess file.

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$$1 [R,L]

Note that: Don’t forget to replace with your site’s domain name.

Here, we have discussed the mostly used rewrite rules and redirect URLs using HTACCESS. If you need any help regarding the .htaccess file, feel free to post your comment below.

Related Articles

Comments 0