Apache .htaccess Redirect WWW

This article was posted more than 1 year ago. Please keep in mind that the information on this page may be outdated, insecure, or just plain wrong today.

Just a few quick notes on how to redirect website to force www or to force just the domain name when users visit your site.

.htaccess Redirect non-WWW to WWW

This will redirect http://my-domain.com/ to http://www.my-domain.com/

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

.htaccess Redirect WWW to non-WWW

This will redirect http://www.my-domain.com/ to http://my-domain.com/

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

#apache