Sunday, June 21, 2009

Apache mod_rewrite and per-host directives / subdomains

This feature of Apache is very powerful and useful. Well, for those who really understand it :) For the rest of us, it is hours of trials-and-fails until we reach wanted configuration.

So, let's say we have a domain (domain.com). We have setup a WildCard DNS records to point to our web server (*.domain.com) and we also have setup our VirtualHost with this wildcards:

ServerName domain.com
ServerAlias *.domain.com

Now, we want to make a translation of
http://sub.domain.com/ to http://www.domain.com/subdomains/sub/

Most of the articles and tutorials I found over the internet are just redirecting requests. So the end-users never actually stay on sub.domain.com, but are transferred to www.domain.com/subdomains/sub . This I don't want. Here is a brief set of rules how to achieve that: http://www.debian-administration.org/article/Wildcard_hosting_with_Apache_and_Bind
They are jsut redirecting.

However I want the end-users to stay on http://sub.domain.com/ however all internal requests to go to http://www.domain.com/subdomains/sub . And also I want it that way only that particular "sub".

And here is the simple solution:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteCond %{HTTP_HOST} ^(sub)\.domain\.com
RewriteRule ^(.*) http://www.domain.com/subdomains/sub/$1 [L,P]

The keypoint here is that is we skip the P flag, mod_rewrite will make automatic external redirect. It is not smart enough to guess that this is our server. That's why we have to put the P-flag, which claims that we want this redirection to take place via "internal Proxy"

Well, that's for now. Hope to post some new stuff soon