How to redirect non-www to www and domain to subdomain?

I recently wanted to permanently redirect all non-www urls to www urls and after that temporarily redirect everything to some subdomain. I found out that all that can be achieved with only few lines in .htaccess file:

# turn rewrite engine on
RewriteEngine On

# permanently (R=301) redirected example.com to www.example.com
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*) http://www.example.com/$1 [R=301,L]

# temporarily (R=302) redirected www.example.com to subdomain.example.com
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*) http://subdomain.example.com/$1 [R=302,L]

 

As simple as that. 🙂