Generic non-www to www (and vice versa) 301 redirect using .htaccess

The problem:
I’ve always hardcoded the domain name in my htaccess’es, requiring me to make changes each time I deploy a new website.
The solution:
Behold, an alternate, generic method of redirecting non-www to www and www to non-www, requiring no changes between deployments!
Non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) http://www.%{HTTP_HOST}/$1 [R=301,L]
www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]
Bonus tip: Remove trailing slash from address line
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

Tags: , , ,