Back htaccess

htacess redirect non-www to www or other way around

WRITTEN BY ON 07 Mar 2011
11,884 VIEWS • SHARES
2 comments

A simple htaccess code to redirect your website from www to non-www or vice versa. It's important concept in SEO because most of the search engine will treat www and non-www as separate website. As a result, you want all the traffics focus on a single domain name, thus, this htaccess code is a good snippet to know.

Apache

from non-www to www

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

Apache

from www to non-www

RewriteEngine on
RewriteCond % ^www.yourdomain.com [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

2 comments
Joe 13 years ago
This will send https to http you need to add in a Rewrite Cond that checks HTTP_HOST vs HTTPS_HOST or the port number to make sure you are dealing with the proper protocal in the redirect.

RewriteCond %{HTTP_HOST} !^www.domain.com [NC]
Or
rewriteCond %{HTTPS} ^on$
Reply
Yolanda 9 years ago
Great resource! Maybe you forgot to close [L,R=301 ?
Reply