Mapping a subdomain to content or folder of main domain with .Htaccess file

Posted by Damodar Bashyal on April 28, 2012


I wanted to create subdomains for all the categories listed here. It was not possible with shared hosting with previous web hosting provider. So, I moved to media temple and they support wildcard subdomain.

So, today I generated all the subdomains to test with all the categories here:

But all of them were displaying homepage content as I had not modified the .htaccess file. So I added this:

RewriteCond %{HTTP_HOST} (.+)\.learntipsandtricks\.com [NC]
RewriteRule ^(.*)$ /blog/c/%1/$1 [L]

Still they were displaying homepage content, so I printed the $_Server variable and found that request_uri was '/' not '/blog/c/search-engine-optimization'.

After going crazy for a while I found out that there is [P] flag which is my friend for this purpose :-)

So, I modified above from [L] to [P] and it worked as expected:

RewriteCond %{HTTP_HOST} (.+)\.learntipsandtricks\.com [NC]
RewriteRule ^(.*)$$1 [P]

I wanted to skip www urls though, so excluded www urls like this:

RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC]
RewriteCond %{HTTP_HOST} (.+)\.learntipsandtricks\.com [NC]
RewriteRule ^(.*)$$1 [P]

I have separate www redirection for handling www and non-www urls.

NOTE: For [P] flag it should always be full url. see from apache website:

Use of the [P] flag causes the request to be handled by mod_proxy, and handled via a proxy request. Use of the [P] flag implies [L] - that is, the request is immediately pushed through the proxy, and any following rules will not be considered. You must make sure that the substitution string is a valid URI (typically starting with http://hostname) which can be handled by the mod_proxy. If not, you will get an error from the proxy module. Use this flag to achieve a more powerful implementation of the ProxyPass directive, to map remote content into the namespace of the local server.

not published on website

QR Code: Mapping a subdomain to content or folder of main domain with .Htaccess file