Todays .htaccess tip – How to use the www. subdomain

There is a good  reason to use www.domain.tld as your primary site, Cookie less subdomains for static content.

Today i will show you a rewrite that will redirect you to www.domain.tld if no subdomain is used:

 

RewriteEngine On
RewriteCond %{HTTP_HOST} !^(.+\.)([a-zA-Z0-9-]+\.([a-z]{2,4})|co\.uk|me\.uk|org\.uk|priv\.no)$
RewriteCond %{HTTP_HOST} ([a-zA-Z0-9-]+\.([a-z]{2,4})|co\.uk|me\.uk|org\.uk|priv\.no)$
RewriteRule ^(.*)$ http://www.%1/ [L,QSA,R=301]

So let me explain to you what this rewrite does:

First thing we do is turn on the rewrite engine.
The following line could be translated to: “if the domain does not have a subdomain”

RewriteCond %{HTTP_HOST} !^(.+\.)([a-zA-Z0-9-]+\.([a-z]{2,4})|co\.uk|me\.uk|org\.uk|priv\.no)$

 
This line saves the domain to the variable %1:

RewriteCond %{HTTP_HOST} ([a-zA-Z0-9-]+\.([a-z]{2,4})|co\.uk|me\.uk|org\.uk|priv\.no)$

 

And last but not least we do the write to www.domain.tld and include the querystring so that we don’t break old links.
The redirect is ofc a permanent redirect, so make sure to clear your browser cache if you make any changes to the rewrite.

RewriteRule ^(.*)$ http://www.%1/ [L,QSA,R=301]

 

Todays .htaccess tip – How to get rid of the www. subdomain

#www. is overrated
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^(.*)  http://%1/$1 [QSA,L,R=301]

Now let’s explain how this works:

The first line is a comment, that explains what the rewrite is supposed to do.

This line just turns on the rewrite engine

RewriteEngine On

This line says if the domain is “www.anything” and note that it saves the domain without the www. part as %1

RewriteCond %{HTTP_HOST} ^www\.(.*)

now this line does the actual rewriting. from anything to the domain with the query string attached (QSA) so we won’t break links. also note that it is a permanent redirect (the R=301 part) and it’s the last rule (L) that will be executed for this request.

RewriteRule ^(.*)  http://%1/$1 [QSA,L,R=301]