I have found some very useful code:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
from another Stack Overflow post:
Remove WWW prefix from your website.
I often re-use the same code on various sub-domains and sites so decided to rewrite a generalised version. I came up with the following:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
It appears to work, but can anyone give me a reason why I should not use this? Have I missed an obvious flaw?
Edit: I am aware that removing the www has associated issues, but in this case I am more interested in problems arising from writing a generalised htaccess RewriteRule (rather than the actions of the rule itself)
Edit: Code edited as recommended by @ulrich
I would also escape the
.otherwise it would matchwww2.somedomain.comand your %1 would end up being.somedomain.com(if you had such a subdomain configured in the future)If you want to further limit it to just a .com you could use
or .net etc
You may also want to add a
RewriteBase /after the RewriteEngine On in case you add other rules to your .htaccess later that need it.Barring those cases, it should work as is.