.htaccess Remove WWW from URL + Directories

Cycododge picture Cycododge · Jun 29, 2011 · Viewed 63.2k times · Source

This seems to be a non-issue for many people (read: I can't find an answer), but I would like to update the following htaccess code to not only remove the 'www' from the URL, but also any sub-directories that are accessed.

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

With this, http://www.example.com/any/ resolves fine, but I want it to redirect to http://example.com/any/ as with the root.

Answer

phpmonkey picture phpmonkey · Jan 2, 2012

I had the same problem (trouble stripping 'www' from URLs that point to a sub-directory on an add-on domain), but after some trial and error, this seems to work for me:

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