Apache RewriteRules for www/no-www

Last month a collegue asked me, how to set up .htaccess RewriteRules which are unaware of hard-coded domain names.

Lots of testing and emptied coffee mugs later, following rules where the results.

www --> no-www - domain unaware

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

Explanation:

  • L1: Ensure that the RewriteEngine is on.
  • L2: If HTTP_HOST begins with "www." then ...
  • L3: catch the path and rewrite it to HTTP_HOST+path for the next step ([C] = chain)
  • L4: and do a sub match (.*) to isolate the "www."-part of the whole pattern. Additionally return a permanent redirect (R=301), so search engines can change there old pathes in index.

This rule set was the hardest part and I'm happy about that we found this solution. Especially for multi-domain environments this is very useful -- you need only one file for many domain www-redirection stuff.

no-www --> www - domain unaware

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

Explanation:

  • L1: Ensure that the RewriteEngine is on.
  • L2: If HTTP_HOST begins not with "www." then ...
  • L3: catch the path and rewrite it to HTTP_HOST with preprended "www." and add path.

This rule is the most common example, but I mention it, too. For completion. And as a self-reminder.

catch non-existing files and directories and redirect to root path

This was an extra rule set. I know, it's not a good solution, somebody will ensure 404 error instead.

What does it do? If the requested path is not an existing file or directory, then redirect to root path.

My collegue asked for, so don't blame me! ;o)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .? / [L]

I believe, this rule can be helpful in some cases. But not giving a 404 is not good at all, especially not in search engine context.