--- core/Controller.php.orig	2009-08-08 12:43:29.149346750 -0400
+++ core/Controller.php	2009-08-08 13:15:04.915824750 -0400
@@ -288,6 +288,7 @@
 		$sitesId = Piwik_SitesManager_API::getSitesIdWithAtLeastViewAccess();
 		if(!empty($sitesId))
 		{
+			$sitesId = $this->_sortSiteIdsByRelevance($sitesId);
 			$firstSiteId = $sitesId[0];
 			$firstSite = new Piwik_Site($firstSiteId);
 			if ($firstSite->getCreationDate()->isToday()) 
@@ -323,4 +324,65 @@
 		}
 		exit;
 	}
+
+	/**
+	 * Tries to list the siteIds by matching the current 
+	 * SERVER['HTTP_HOST'] against any of the site names
+	 * 
+	 * if your target site is sub.foo.com or foo.com, but you 
+	 * access piwik from stats.foo.com or foo.com/stats, this 
+	 * method will put foo.com as your default idSite
+	 */
+	protected function _sortSiteIdsByRelevance($idSites) {
+		//if we're running from CLI, just return
+		if (!isset($_SERVER['HTTP_HOST'])) {
+			return $idSites;
+		}
+		$thisSiteList = explode('.', $_SERVER['HTTP_HOST']);
+			$db = Zend_Registry::get('db');
+			$sites = $db->fetchAll("SELECT *
+				FROM ".Piwik::prefixTable("site")."
+				WHERE idsite IN (".implode(", ", $idSites).")
+				ORDER BY idsite ASC");
+
+		$foundMatch = -1;
+		foreach($sites as $k => $v) {
+			//make a copy for comparing
+			$compSiteList = $thisSiteList;
+			$mainUrl = parse_url($v['main_url']);
+			$targetSiteList = explode('.', $mainUrl['host']);
+			//strip off any prefixes, like www. or stats.
+			$sizeDiff = count($compSiteList) - count($targetSiteList);
+			while ($sizeDiff > 0) {
+				array_shift($compSiteList);
+				$sizeDiff--;
+			}
+			//now $compSiteList should be the same length as $targetSiteList
+			//count matches backwards, any match above n-1 and above 1 is good
+			$n = 0;
+			for ($q=count($compSiteList); $q > 0; $q--) {
+				if ($compSiteList[$q-1] == $targetSiteList[$q-1]) $n++;
+			}
+			if ($n >= count($targetSiteList)-1 && $n > 1) {
+				$foundMatch = $v['idsite'];
+				break;
+			}
+		}
+
+		//done with matching
+		if ($foundMatch < 1) {
+			//no matches
+			return $idSites;
+		}
+		//we found something, reorganize the list
+		$newSitesIds = array();
+		foreach ($idSites as $k => $v) {
+			if ($v == $foundMatch) {
+				array_unshift($newSitesIds, $v);
+			} else {
+				$newSitesIds[] = $v;
+			}
+		}
+	return $newSitesIds;
+	}
 }
