Skip to Content Skip to Menu

.htaccess 301 force redirect directory to a subdomain

I recently came across a situation that required some attention with htaccess regex. This example I needed to send a folder on my server to a sub domain that had been created.

Eg. http://www.my-site.com/subfolder/ -> http://subfolder.my-site.com/

.htaccess code snippet:

RewriteEngine On
Options +FollowSymLinks
RewriteBase /

RewriteCond %{http_host} ^my-site.com [nc]
RewriteRule ^(.*)$ http://www.my-site.com/$1 [L,R=301]

#this is the magic line below here
RedirectMatch 301 ^/subfolder/(.*)$ http://subfolder.my-site.com/$1

And that's it! Pretty cool hey.

Other thing to note -> this redirect will also account for subfolders and pages of the first subfolder. Eg. http://www.my-site.com/subfolder/nextfolder/a-page.php -> http://subfolder.my-site.com/nextfolder/a-page.php