Serve main domain from subdirectory with .htaccess
If you are running your site on a shared hosting and you have multiple domain installed as subdirectories the things could go out of hand really fast. In my specific case I have multiple installs of different CMS and one main domain running from “root” directory. What I wanted was to be able to run all of my domain in separate sub folders. Here is the solution:
[cc lang=”text”]
RewriteEngine on
# Part 1
RewriteCond %{HTTP_HOST} ^(www.)?topdomain.com$ [NC]
RewriteCond %{REQUEST_URI} !^/topdomain/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /topdomain/$1
# Part 2
RewriteCond %{HTTP_HOST} ^(www.)?topdomain.com$ [NC]
RewriteRule ^(/)?$ topdomain/index.php [L]
[/cc]
In first part I detect the domain, check if the doesn’t match our subdirectory, make sure that the URL doesn’t match any existing file or directory and last serve whole request from our subdirectory passing all other request parameters that may come with the original URL.
The second part serves any request to our top level domain that has no parameters to the index files in our designated sub directory this is needed because that rule would be skipped in first conditions because our root is existing directory.
So just replace the domain and the subdirectories and you are ready to go.
Extremely nicely written post, thanks!