Apache Redirect folder to subdomain

A client had an application at www.example.com/dir. They have now set up a subdomain at dir.example.com. The subdomain references the files stored at www.example.com/dir. They'd now like people accessing www.example.com/dir to be redirected to dir.example.com.

I'm guessing I need a .htaccess to sit in www.example.com/dir and if it's accessed with www, redirect to the subdomain, just not sure of the syntax.


Solution 1:

Add a .htaccess to the directory belonging to www.example.com/dir:

RewriteEngine on
RewriteCond ${HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*) http://dir.example.com/$1 [R,L]

The first line enables mod_rewrite, the second line checks that the current request is using hostname www.example.com to access the resource, and the third line redirects all such requests to the desired target hostname.

Solution 2:

What about simply:

Redirect /dir http://dir.example.com

Solution 3:

Try this rule in a .htaccess file in your /dir directory:

RewriteCond %{HTTP_HOST} !=dir.example.com
RewriteRule .* http://dir.example.com/$0 [L,R=301]

Or this rule in your root directory:

RewriteCond %{HTTP_HOST} !=dir.example.com
RewriteRule ^dir(/(.*))?$ http://dir.example.com/$2 [L,R=301]