mod_rewrite:
RewriteCond %{HTTP_HOST} ^foo.example.com$ [NC]
RewriteCond %{REQUEST_URI} !^/foo/.*$
RewriteRule ^(.*)$ /foo/$1 [L]

PHP
<?php
$where = $_SERVER["HTTP_HOST"]; 
if($where == "foo.example.com"){ 
	header("Location:https://$where/foo/"); 
}elseif($where == "bar.example.com"){ 
	header("Location:https://$where/bar/"); 
}else{
	header("Location:https://$where/index.html"); 
}
?>

ASP
<%
sname = Request.ServerVariables("SERVER_NAME")
sname = lcase(sname)
if InStr(sname,"foo.example.com") <> 0 then
	response.redirect "foo/"
else
	if InStr(sname,"bar.example.com") <> 0 then
		response.redirect "bar/"
	else
		response.redirect "index.html"
	end if
end if 
%>

ColdFusion
<CFIF FindNoCase("foo.example.com","#CGI.SERVER_NAME#") GT 0>
	<CFLOCATION URL="/foo">
<CFELSEIF FindNoCase("bar.example.com","#CGI.SERVER_NAME#") GT 0>
	<CFLOCATION URL="/bar">
<CFELSE>
	<CFLOCATION URL="/index.html">
</CFIF>

JavaScript
<script language="JavaScript" type="text/JavaScript">
	function redirect(){
		var loc = location.href.split(':');
		if(loc[0]=='http'){
			location.href='https:'+loc[1];
		}
	}
	onload=redirect
</script>

ASP.NET
private void Page_Load(object sender, System.EventArgs e)
{
If (Request.ServerVariables["SERVER_NAME"] == "foo.example.com") then
	Response.Status = "301 Moved Permanently";
	Response.AddHeader("Location","https://foo.example.com/foo");
end if
}