Using mod_rewrite rules for subdomains to subfolders

A URL address bar with www

From the land of things that were harder than they needed to be. Seems like you need a deep dive in everything to be able to do anything sometimes.

So, on this domain I wanted to use a single host to handle a few subdomains. One for my blog (which you’re on now), and maybe a couple of others for web classes or anything else I may want to mess around with.

Easy enough to do with subdomains and different document root folders on a standard server. And the hosting service does provide different document root folders. I ended up with different FTP root folders for each subdomain which is not what I was looking for. I wanted to use one FTP account and then just upload to the location I wanted for the subdomain I was updating. 

So I decided to use .htaccess to redirect subdomains to subfolders in the document root.I also wanted wordpress in a subfolder of it’s own like the image below:

This presented a problem with having and end up in the /wp directory, and then having other subdomains (demo / test) end up in their respective directories.

.htaccess flag explanations can be found here:

And lots of other interesting facts here:

Here’s how I got this working (with comments):

IndexIgnore *
RewriteEngine On


#redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

#Rewrite * to subdirectory ignoring case
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com [NC]
RewriteRule ^(.*)$$1 [L,NC,QSA]

#Rewrite primary domain to wordpress
RewriteCond %{REQUEST_URI} !^/.*/
RewriteCond %{HTTP_HOST}$ [NC]
RewriteRule ^(.*)$$1 [L,NE,R=301]


Hopefully that helps. The nice part about this is I have one FTP account to deal with, any new subdomains I add all I have to do is point DNS to the host and add a folder to the root directory that matches the subdomain name.

Would you want this in production? Not likely, but this is just my domain with some junk and a blog…  🙂

Leave a Reply

Your email address will not be published. Required fields are marked *