17 August 2005

Recipe for Apache's mod_rewrite and www independence

Note that ww.domainname and wwww.domainname work just as well, so if you define these in your DNS, people who make a typoe will still reach you. With a little more work, you can redirect them to either www.domainname or plain domainname without any w’s at all.

UseCanonicalName Off

LogFormat "%V %h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\"" vcommon
CustomLog logs/access_log vcommon

RewriteEngine on
RewriteLog "/var/log/httpd/rewrite_log"
RewriteLogLevel 0

RewriteMap lowercase int:tolower

RewriteCond %{REQUEST_URI} ^/icons/
RewriteRule ^/(.*)$ /var/www/$1 [L]

RewriteRule ^(.+)$ %{lowercase:SERVER_NAME}$1
RewriteRule ^w*\.(.+)/(.*)$ /var/www/virtual/$1/$2 [L]
RewriteRule ^(.+)/(.*)$ /var/www/virtual/$1/$2 [L]

Et viola! Dump a website’s files in /var/www/virtual/domainname/ and define a DNS entry for it, and she’s apples. For the terminally lazy (like me), you can even define a wildcard A-record so all you need to do to add a site is dump a directory full of files in /var/www/virtual/.

For the ultimate in laziness, add a “www” directory to the new-user skeleton and make the RewriteRule path /home/$1/www/$2 instead. Now adding a new domain involves “useradd domainname and “passwd domainname (or do the same through webmin).

Another interesting trick is to hand out your favicon.ico image to every site hosted on the machine by first providing an ErrorDociment just for the icons:

<Files favicon.ico>
ErrorDocument 404 /favicon-fallback.ico
</Files>

...then defining a RewriteRule to point every site’s /favicon-fallback.ico URI to your common favicon.ico (put this in front of the RewriteRule above if you’re using both):

RewriteCond %{REQUEST_URI} ^/favicon-fallback.ico
RewriteRule ^/(.*)$ /var/www/virtual/yourmainwebdomain/favicon.ico [L]

No comments: