Skip to main content

apache 2.2 - How to use htaccess to rewrite to new base directory for files



So I have a subdomain, sub1.example.com, that is mapped to a directory located in the server's root:
/subdomains/sub1/httpdocs/



I have another subdomain, sub2.example.com, that is mapped to a different directory:

/subdomains/sub2/httpdocs/



It's at a hosting company that won't let me alter Apache conf files.



I want to use the .htaccess file to allow sub2 requests to be processed by the files that are located in the sub1 directory. Almost like a symbolic link. I need to preserve the hostname. So http://sub2.example.com/test.php would access the same file as http://sub1.example.com/test.php, but the hostnames would be preserved.



I tried the following in /subdomains/sub2/httpdocs/.htaccess:




RewriteEngine On

RewriteRule ^(.*)$ /subdomains/sub1/httpdocs/$1


but I'm a getting internal server error.



Any suggestions?


Answer



The ^(.*)$ pattern captures the complete path component of the URL which always begins with a /, therefore you should probably remove the last / from your RewriteRule. This is how it should be:



RewriteEngine On

RewriteRule ^(.*)$ /subdomains/sub1/httpdocs$1


Or make the pattern match everything except the first /:



RewriteEngine On
RewriteRule ^/(.*)$ /subdomains/sub1/httpdocs/$1

Comments