Wednesday, June 6, 2007

Apache Rewrite: From Subdomain to Subfolder

Source: http://www.webmasterworld.com/apache/3163397.htm

rkrause


#:3165292
6:10 pm on Nov. 22, 2006 (utc 0)

Here's an alternative solution. It bypasses the need for specially-named subdirectories and it creates an environment variable with the subdomain name for later reference.

This solution avoids the 'directory occlusion' side-effect of the above example. (That is, nominally, if the the REQUEST_URI references a directory path with the same name as the current subdomain's directory path, then that subdirectory should still be processed by the rewrite rule). This solution also allows you to easily determine whether the page was accessed via the subdomain (by simply checking the environment variable, SUBDOMAIN, in a CGI script or SSI page). Additionally, this solution verifies that the subdomain has its own directory, and, if not, then it defaults to the main website under the document root (in which case SUBDOMAIN will be set to an empty string).

RewriteBase /

#### URL Rewrite Handler for Subdomains (by Randall Krause) ####

RewriteCond %{ENV:REDIRECT_SUBDOMAIN} =""
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.mydomain\.org\.?(:80)?$ [NC]
RewriteCond %{DOCUMENT_ROOT}/subdomains/%1 -d
RewriteRule ^(.*) subdomains/%1/$1 [E=SUBDOMAIN:%1,L]
RewriteRule ^ - [E=SUBDOMAIN:%{ENV:REDIRECT_SUBDOMAIN},L]


Note, that I have tested this code, and it is almost identical to what I use on my production server which is why I have strict input validation (remember the HOST field can be forged with any falsified or corrupt data, so it is important to verify that it complies with the HTTP/1.1 specification, esp. if your primary site is on its own IP address, in which case Apache most likely hasn't even validated the HOST header). Note that on some shared-hosting configurations, I've found that DOCUMENT_ROOT may not be correct until the first rewriting phase is complete (for who knows what reason) so you may have to hard-code the path.

You will need to change "mydomain\.org" to your actual domain name. If your subdomain directories are to be located someplace other than "subdomains/%1", then you will want to modify the actual path to the subdomains based off of the document root.

--Randall


No comments: