Want to create dynamic subdomain in codeigniter?

2019-01-17 17:56发布

问题:

In my site i want to add an functionality for user to use their username with domain.

Like in codeigniter right now i want to give the user to use their own url to login in site and do other stuff.

For eg:

i Want www.username.mysite.com/login or www.username.mysite.com/category

so here the user can login with their credential and add the category. so i have two controller in my site with login and category.

So how to do this with the routes Or .htaccess.

回答1:

Use this code in server Vhost file:

<VirtualHost *:80>
    DocumentRoot "/home/yourdoma/public_html/yourdomain"
    ServerName yourdomain.com
    ErrorLog "logs/yourdomain.local-error.log"
    CustomLog "logs/yourdomain.local-access.log" common
    <Directory "/home/yourdoma/public_html/yourdomain">
        AllowOverride All
        Require all Granted
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/yourdoma/public_html/yourdomain"
    ServerName dummy-host.yourdomain.com
    ErrorLog "logs/yourdomain.com-error.log"
    CustomLog "logs/yourdomain.com-access.log" common
    ServerAlias *.yourdomain.com
    <Directory "/home/yourdoma/public_html/yourdomain">
        AllowOverride All
        Require all Granted
    </Directory>
</VirtualHost>

and For your codeigniter config file:

$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$schema = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'].'://' : 'http://';
$spl_host = explode("mysite.com", $host);
$subhost = '';
if (count($spl_host) == 2) {
    $subhost = current($spl_host);
}

if($host == $subhost.'mysite.com') {
    $config['base_url'] = $schema.$subhost.'mysite.com';
} else {
    $config['base_url'] = $schema.$host;
}


回答2:

here's an explanation of your issue here. http://www.joehayes.org/setting-up-wildcard-dns-for-subdomains.html

Ok if you have read the explanation on the link, you'd know that you should redirect all of your subdomains to www first. in httpd.conf file there's a virtual host definition containing only yourdomain.com to redirect all the requests to your DocumentRoot.

**ServerAlias yourdomain.com**
ServerAdmin webmaster@yourdomain.com
DocumentRoot /home/yourdoma/public_html
BytesLog domlogs/yourdomain.com-bytes_log
ServerName www.yourdomain.com
User yourdomain
Group yourdomain
CustomLog /usr/local/apache/domlogs/yourdomain.com combined
ScriptAlias /cgi-bin/ /home/yourdomain/public_html/cgi-bin/

and you should modify the ServerAlias to *.yourdomain.com to retrieve all subdomains into your Document Root folder. then you should be able to mod_rewrite or url parse your uri to succeed this.