301 Redirect

Redirect domain.com to www.domain.com

Most of the website can be accessed with www.domain.com and domain.com. Since Google penalizes this due to duplicated content reasons, you have to stick your domain to either www.domain.com or domain.com

Many links are outside of your website scope and the search engines already have indexed your website under both addresses, you can't change that easily.

You can use .htaccess file to redirect all requests for domain.com for www.domain.com

Redirect domain.com to www.domain.com

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

Redirect www.domain.com to domain.com

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^domain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

How the code works ?

RewriteEngine On
RewriteBase /

The first two lines just say apache to handle the current directory and start the rewrite module.

RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]

Specifies that the next rule only fires when the http host is NOT (specified with the "!") www.domain.com. The ^ means that the host starts with www.domain.com, the $ means that the host ends with www.domain.com - and the result is that only the host www.domain.com will trigger the following rewrite rule. Combined with the inversive "!" is the result every host that is not www.domain.com will be redirected to this domain.

The [NC] specifies that the http host is case insensitive.

RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

Describes the action that should be executed:

The ^(.*)$ is a little magic trick. The dot represent any character in regular expression. So .* means that you can have a lot of characters, not only one. This is what we need - because this ^(.*)$ contains the requested url, without the domain. The next part http://www.domain.com/$1 describes the target of the rewrite rule - this is our "final", used domain name, where $1 contains the content of the (.*).

The next part is also important, since it does the 301 redirect for us automatically: [L,R=301]. L means in this is the last rule in this run - so after this rewrite the webserver will return a result. The R=301 means that the webserver returns a 301 moved permanently to the requesting browser or search engine.

Get in touch with us

Questions? Concerns? Comments? We want to hear from you!
Drop us a line with whatever is on your mind and we will get back to you ASAP!!