2011-12-27 26 views
0

我在codeigniter中創建一個SaaS web應用程序,我試圖根據子域是否存在來確定如何路由到特定的控制器。Codeigniter - 如何根據子域名是否存在來路由控制器

目前我擁有它,所以如果你把網址subdomain.example.com,我的默認控制器檢查url中的子域是否存在於數據庫中,如果不存在,它會顯示錯誤頁面。

public function __construct() 
    { 
     parent::__construct(); 
     $subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2); //creates the various parts 
     $subdomain_name = $subdomain_arr[0]; //assigns the first part 
     //echo "subdomain_name = $subdomain_name"; 

     // if the subdomain does not exist, redirect to error page 
     if(!$this->subdomainExists($subdomain_name)) { 
      redirect('error/index'); 
     } else { 
      $this->subdomain = $subdomain_name; 
     } 
    } 

其中一個用戶進入一個子域,但現在如果用戶輸入一個URL沒有一個子域,如example.com,我想使用一個不同的控制器這偉大工程的URL。

達到此目的的最佳方法是什麼?我正在考慮做以下事情,但似乎並不是每次有人去example.com都會發生重定向。

// if no subdomain was entered, redirect to controller 'aDifferentController' 
// else if a subdomain was entered, check that it exists in the database and if not redirect to an error page. 
if(the url entered does not contain a subdomain) { 
    redirect('aDifferentController'); 
} else if(!$this->subdomainExists($subdomain_name)) { 
    redirect('error/index'); 
} else { 
    $this->subdomain = $subdomain_name; 
} 

回答

3

爲什麼不有條件地聲明基於子域的路由。

在routes.php文件

,做到這一點

if (strstr($_SERVER['HTTP_HOST'], 'some-subdomain.mydomain.com')) { 
$route['uristring'] = "controller/method"; 
} 
+0

看起來像一個非常好的主意。我會試試這個。我寧願這樣做比總是做重定向。 – Catfish 2011-12-28 04:45:27

+0

工作真棒。感謝你這麼好的想法。 – Catfish 2011-12-28 21:37:46

0

你需要制定出最可能的情況是什麼,更多的人可能去的子域,都被他們更有可能去到主網站?

如果他們更有可能去主網站,然後做一個檢查,如果子域存在,如果它確實然後重定向到另一個控制器,否則,繼續。

如果他們更有可能去子域,然後檢查是否存在子域,如果它確實不是然後重定向到另一個控制器,否則繼續。

另一種選擇(也許我認爲更好)是在使用.htaccess進行重定向之前,它甚至會點擊代碼點火器,但這取決於您對服務器的訪問級別。

+0

這將是子域名的網站和非現場的子域約50/50。 – Catfish 2011-12-27 23:11:14

+0

然後真的無論哪種方式工作,但如果您使用的是Apache,我仍然投票支持.htaccess版本。 – Hailwood 2011-12-27 23:26:45

+0

有沒有什麼辦法可以使用路由,或者只是在base_url之後的部分url? – Catfish 2011-12-27 23:29:39

相關問題