Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache and mod_rewrite: Redirect domain to subdirectory

(I know this is not a programming question per se, but it involves regular expressions, so at least it is borderline... )

The setup:

Apache 2.0 with mod_rewrite on Windows. Two domains, let's call them domain1.example and domain2.example. I would like to host both domains on the same server ("server1"), so I point them to the same IP address.

Now, if the user types "domain2.example" into his browser, I want him to end up in a subdirectory** on the server, but leave the domain he typed intact ("domain2.example/domain2/"). The redirection must leave all absolute and relative links on pages under this domain/directory intact, of course.

Is this possible with mod_rewrite (or Apache virtual hosts or other method), and how do I do it?

** The "subdirectory" in this case is not actually a file folder on disk, but a virtual folder made with the Apache "Location" directive.

Thanks.

like image 773
ObiWanKenobi Avatar asked Apr 22 '09 05:04

ObiWanKenobi


2 Answers

I'm assuming you don't have access to the Apache configuration, otherwise, yes, virtual hosts are your best option. If you don't, however, this can be put in a .htaccess file and should do the trick:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.+)\.yourwebsite\.com$
RewriteRule ^/(.*)$ /path/to/your/subdomains/%1/$1 [L]

So a request to http://foo.yourwebsite.com/bar would go to /path/to/your/subdomains/foo/bar

like image 105
Bill Fraser Avatar answered Nov 15 '22 09:11

Bill Fraser


Assuming that the domains are independend the advised solution is virtual hosts.

You can find the documentation at the apache website.

like image 42
Peter Smit Avatar answered Nov 15 '22 08:11

Peter Smit