htaccess: Remove www from URL without specifying the full URL

There is a Mobile Optimized version of this page (AMP). Open Mobile Version.

This is something that has been irritating me for a while now, I like to remove and force removal of the www. in front of all websites that I own and host. However the only examples I have ever found online use the domain name in the re-write rule. Which means that every .htaccess file has to be altered to give the domain name that the site is using.

I have since discovered code which will implement the re-write rule but without explicitly specifying the domain name, you can now redirect all www. pages to non-www without having to specify your domain name in your .htaccess file.


Force removal of www from URL:

Here is the code snippet:

RewriteEngine On

# Force NO www RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]


Force use of www in URL:

And just in case you are looking for the opposite and force www in all URL’s then here is the solution:

RewriteEngine On

# Force YES www

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


Why do either?

It is important that you force one method or the other, as allowing for either could cause problems and inconsistency's.

A few important benefits include:

  • It will avoid duplicate content problems with search engines such as Google.
  • It will avoid the possibility of split page ranking and/or missing rankings.
  • It is nicer and more consistent for you and your visitors.

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments