Dean Williams

htaccess: Remove www from URL without specifying the full URL

You are currently viewing the Mobile Optimized version (AMP), some features may be missing or may not work as expected. Open Full 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:

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