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 ( We have setup a WildCard DNS records to point to our web server (* and we also have setup our VirtualHost with this wildcards:

ServerAlias *

Now, we want to make a translation of to

Most of the articles and tutorials I found over the internet are just redirecting requests. So the end-users never actually stay on, but are transferred to . This I don't want. Here is a brief set of rules how to achieve that:
They are jsut redirecting.

However I want the end-users to stay on however all internal requests to go to . 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} !^$ [NC]
RewriteCond %{HTTP_HOST} ^(sub)\.domain\.com
RewriteRule ^(.*)$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

No comments: