[英]Codeigniter - How to route controller based on whether a subdomain exists or not
我正在codeigniter中創建一個SaaS Web應用程序,並且試圖根據是否存在子域來確定如何路由到特定控制器。
當前,我擁有它,因此,如果您放置一個subdomain.example.com
的URL,我的默認控制器將檢查該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
,我希望使用其他控制器。
實現此目標的最佳方法是什么? 我當時正在考慮執行以下操作,但是每次有人訪問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;
}
為什么不根據子域有條件地聲明路由。
在routes.php中,執行此操作
if (strstr($_SERVER['HTTP_HOST'], 'some-subdomain.mydomain.com')) {
$route['uristring'] = "controller/method";
}
您需要確定最可能的情況是,是否有更多的人去子域,他們是否更有可能去主站點?
如果他們更有可能去到主網站,然后做一個檢查,如果子域存在,如果它不然后重定向到另一個控制器,否則,繼續。
如果他們更有可能去子域,則檢查子域是否存在,如果不存在則重定向到另一個控制器,否則繼續。
另一個選擇(我認為可能更好)是使用.htaccess進行重定向,甚至不會觸發代碼點火器,但這取決於您對服務器的訪問級別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.