Search code examples
codeignitersubdomainwildcard-subdomainsegments

Can the subdomain URL segment be used as a class in Codeigniter?


I need to use a subdomain as a class. ie, instead of:

www.example.com/class/function/ID eg www.example.com/town-name/history/1

I need

class.example.com/function/ID eg town-name.example.com/history/1

I've wildcarded the subdomain in nginx, now I've googled and read

http://codeigniter.com/user_guide/libraries/uri.html

http://codeigniter.com/user_guide/general/urls.html

http://codeigniter.com/user_guide/helpers/url_helper.html

but nothing relevant. I need it to be so that if another town is added to the db, it'll resolve that new town and its details.

I see many discussions about rewrites, redirects etc, but I specifically need to use the subdomain town name as the class variable. If possible, in an idea world, I could use both together, but I doubt that's possible?

I've had it going fine in plain old php for a couple of years now; now I want to upgrade to codeigniter without ruining my old structure if possible (plus there's a good reason for it).

Thanks you.


Solution

  • You can do it. I'm doing it for one of my projects.

    In the constructor of your controller, just explode the current url and get the subdomain and pass it in your method as a variable

    public class Controller extends CI_Controller {
    
        $subdomain = null;
    
        public __construct() 
        {
            // explode url here and set $this->subdomain = the actual subdomain
        }
    
        public function index() 
        {
            if($this->subdomain == null) {
                show_404();
            } else {
                // do what you wish
            }
        }
    }