So it’s all well and good to redirect from one domain to another but how about redirecting to a directory?
I use shared hosting and host 3-4 domains on the same hosting account. To be nice and tidy I like to keep each site in a separate sub folder. There are a few ways I could do this obviously. I could use PHP and do something like the following:
$SiteNameURL = $_SERVER['HTTP_HOST'];
switch (strtolower($SiteNameURL)) {
case "domain.com": //MUST BE LOWER CASE
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/folder/");
break;
case "www.domain.com": //MUST BE LOWER CASE
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/folder/");
break;
}
But that is rather ugly and it would be nice to keep all the redirecting in one place.
This is what I came up with:
#Turns the rewrite engine on.
RewriteEngine on
#Fix missing trailing slash character on folders.
RewriteRule ^([^.?]+[^.?/])$ $1/ [R,L]
#www.domain.com and domain.com will map to the folder {root}/folder1/
RewriteCond %{HTTP:Host} ^(?:www\.)?domain\.com$
RewriteCond %{REQUEST_URI} !^/folder1/
RewriteRule ^(.*) folder1/$1 [NC,L,NS]
There is a little bit of regex involved but if you step through line by line it’s really fairly simple. Of course the last 4 lines are what matters for me. I added them to my “.htaccess” file from my first post on Mod_rewrite.
