Cấu hình subdomain với DNS, Apache và các sử dụng trong PHP



I’ve been wondering for a while if I can do automatic subdomain using username, same as WordPress MU does. Some thought come across and all leads to same point , the $base_url() variable.

What makes me a bit wary is that particular variable reside in config file, which suppose to be static. On the other hand, manipulating the variable in controller is easy but redundant. So what the heck…
There are three places to modify for this :

  1. DNS entry
  2. Apache vhost
  3. Codeigniter config.php

Life has been good to me since I have full control over those three, I have my own DNS server, and apache server, so if you are less fortunate than I am, do not hesitate to nag , beg and annoy your hosting company to do changes for you

DNS entry :

make sure you put wildcard entry :
mygreatsite.com. A
*.mygreatsite.com. A

Apache vhost :

We use separate vhost file for each domain, and include those files using Apache “Include” directive, to keep things tidy and avoid fiddling with main apache config.
ServerName mygreatsite.com
ServerAlias *.mygreatsite.com
ServerAdmin superduperadmin@superduperwebcompany.com
#RedirectMatch 301 (.*) http://mygreatsite.com$1
DocumentRoot /var/oi/keepcodeigniterhere
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all

the most important part is :
#RedirectMatch 301 (.*) http://mygreatsite.com$1
CodeIgniter config.php :

I test using this simple hack ( on the config.php ) :
$config['base_url'] = “http://”.$_SERVER["HTTP_HOST"];

And wala !! I can test using whatever.mygreatsite.com and codeigniter still working as if there is nothing wrong with $base_url variable, therefore you can use any words ( hence, wildcard ) as subdomain prefix and apache will direct the request to the same codeigniter installation. Next step I will do is using username as subdomain, eliminating ugly url like
and make it nicer as in
Nice !!
Yeah I know I have to test rigorously to ensure nothing is broken with codeigniter ( and my application ) but at this moment I think it leads to the right direction.
I also do some search at CodeIgniter’s forum just to verify my method and I’ve found great reference :

For wildcard DNS, take a look at this guide by WordPress creator :


Trả lời

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Đăng xuất / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất / Thay đổi )

Connecting to %s