30 Apr

How to redirect url with or without www in htaccess

redirect url with or without www in htaccess

Normally every website domain is accessible with or without www (mydomain.com or www.mydomain.com). We will get the same pages & there will be no difference. But Google will consider it as duplicated content and it will affect your Search Engine Optimization ranking. So we should define a preferred domain method with the help of htaccess. It will redirect the access to either with or without www. Alternatively, add canonical URL ( <link rel=”canonical” href=”http://www.mydomain.com” /> ) in your page head and don’t forget to choose a preferred domain in Google Webmaster Tools.

Here i’m going to show you how to define a preferred domain method in htaccess.

Redirect mydomain.com to www.mydomain.com:

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

Redirect www.mydomain.com to example.com:

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

Redirect IP to www.example.com:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^12\.34\.56\.789$
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [L,R=301]

 

Sanju
Follow me

About Sanju

I’m Sanjunath.S from Mumbai, India. I like web technologies, traveling & history. I have 11+ years of experience in web technologies like HTML 5, CSS 3, JavaScript, Bootstrap, and PHP.




Pay with PayPal
Translate »