Home  ›  Programming  ›  Redirect all but used subdomains to primary domain using mod_rewrite and CodeIgniter

Tags: , , , , , , ,

Redirect all but used subdomains to primary domain using mod_rewrite and CodeIgniter

I was recently playing with mod_rewrite and wanting a couple of subdomains to act as subdomains, but all others to redirect back to my site without the leading “www”. For example:

www.example.com => example.com
bad.example.com => example.com
api.example.com => api.example.com

Not being a regular expression or mod_rewrite expert (or any resemblance of such), this was a bit of a challenge. But I did it with the help of a mod_rewrite and regular expression cheat sheet, as well as the excellent Apache URL Rewriting Guide.

So here it is for anyone else that could benefit. Just replace the bold parts with your own subdomains (and example with your domain).

Redirect without leading www:

Redirect with leading www:

If you’re using CodeIgniter and mod_rewrite for pretty URLs, you’ll need to be sure to add these subdomains to the list of directories that can be accessed directly.


3 Responses to “Redirect all but used subdomains to primary domain using mod_rewrite and CodeIgniter”

  1. Thanks for this article. It’s a helpful start.

  2. Aerian says:

    i have an application developed in codeigniter .
    if i’ll write domin.com or domain.net i want my application run same application how i map thi

  3. Good article, I wonder if you can help me with this a little.

    I want to redirect subdomains so that they become a parameter to a CI controller. For example:-

    subdom.mydomain.com
    becomes
    http://www.mydomain.com/index.php/mycontroller/subdom/

    and

    subdom.mydomain.com/param
    becomes
    http://www.mydomain.com/index.php/mycontroller/subdom/param

    Any hints would be great, i’ve struggled with this, but just can’t seem to get my head around mod_rewritting!

Help us improve the wiki Send Your Comments