Codeigniter - How to route controller based on whether a subdomain exists or not

一笑奈何 提交于 2019-12-25 04:18:01

问题


I'm creating a SaaS web app in codeigniter and i'm trying to determine how to route to a specific controller based on whether a subdomain exists or not.

Currently I have it so if you put a url of subdomain.example.com, my default controller checks whether the subdomain in the url exists in the database, and if it does not, it displays the error page.

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;
        }
    }

This works great for urls where a user enters a subdomain, but now if the user enters a url without a subdomain such as example.com, I want a different controller to be used.

What is the best way to achieve this? I was thinking of doing the following, but it doesn't seem best to have a redirect occuring every time someone goes to 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;
}

回答1:


Why not conditionally declare routes based on the subdomain.

in routes.php, do this

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



回答2:


You need to work out what the most likely scenario is, are more people likely to go to the subdomains, are are they more likely to go to the main site?

If they are more likely to go to the main site then do a check if the sub domain exists, if it does then redirect to the other controller, else, continue.

If they are more likely to go to the sub domains then check if a sub domain exists, if it does not then redirect to the other controller, else continue.

The other option (and possibly better in my opinion) is to do the redirect using .htaccess before it even hits code igniter, but that depends on what level of access you have to your server.



来源:https://stackoverflow.com/questions/8649858/codeigniter-how-to-route-controller-based-on-whether-a-subdomain-exists-or-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!