Subdomain based on CodeIgniter controller name

2019-02-11 04:21发布

问题:

Suppose I have this two different module for the site that is under two different controllers. Like, index.php/controller1/... and index.php/controller2/...

Now, is it possible to have one of the controller URL in a subdomain? To make it clear, in this example, is it possible to have say, index.php/controller1/... in a URL like mainwebsite.com/... and index.php/controller2/... in another URL like controller2.mainwebsite.com/ ?

If so, what's the best way to do it? routes.php or .htaccess? And in either case I will appreciate a little help on how to do it, if you can point me to a relevant link, that will also be helpful.

回答1:

In my opinion, what you're trying to do is a bit silly, but, I guess it's not my place to say.

Here are your options as far as I see it:

Modify your apache config or .htaccess file to redirect calls to a specific subdomain to a specific controller using mod_rewrite:

For instance (I haven't tested this):

RewriteEngine on
RewriteCond %{HTTP_HOST} ^blog.example.com$
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt)
RewriteRule ^(.*)$ /index.php/blog/$1 [L]

That should at least point you in the right direction, I think. Of course, this assumes that your subdomain is pointed to the same IP address and the apache virtual hosts are setup to point that subdomain to the same directory as your normal domain.

You'll also need to point all your links to the subdomain and omit the controller. So, if the URL would normally be: http://www.example.com/blog/cat/awesome then you'll need to make the link point to http://cart.example.com/cat/awesome . So, you're not going to be able to use the nice helper functions like site_url('cart/cat/awesome') anymore--that would be a major turn off for me.

I hope that makes sense.

Setup your CI instance to support multiple apps and just have the subdomain point to the appropriate app directory

For more information: http://codeigniter.com/wiki/Multiple_Applications/

Do some crazy stuff with the Route class:

In your routes.php config file:

if(preg_match('/^blog/',$_SERVER['HTTP_HOST'])) {
    $route['(:any)/(:any)/(:any)/(:any)'] = 'blog/$1/$2/$3/$4';
    $route['(:any)/(:any)/(:any)'] = 'blog/$1/$2/$3';
    $route['(:any)/(:any)'] = 'blog/$1/$2';
    $route['(:any)'] = 'blog/$1';
    $route['blog'] = 'blog/index';
}

If any of your pages require more than 4 URI parts, just add another line at the top of the route rules. I don't even know if this would work, per se... but it might. I'd definitely give it a shot as it would be the least amount of work more than likely.