简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM