There is a project that requires me to make the following domain redirection:

  • Redirect all users to access the site WITHOUT the 'www.' prefix for all subdomain.
  • Redirect all users to access the site WITH the 'www.' prefix for main domain only.

To fulfill this purpose, I simply add a few lines of code to the htaccess file:

RewriteEngine on

# Redirect the 'www.' version of the subdomains.
RewriteCond %{HTTP_HOST} ^www\.([^.]+)\.example\.com [NC]
RewriteRule ^(.*)$ http://%1.example.com/$1 [R=301,L]

# Redirect the non 'www.' version of the main domain.
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

For general use, the following is the code to redirect visitors from non www to www or vice versa.

Redirect all users to access the site WITH the 'www.' prefix:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Redirect all users to access the site WITHOUT the 'www.' prefix:

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]