Muffinresearch Labs by Stuart Colville

Redirecting subdomains to directories in apache. | Comments (22)

Posted in Hosting, Linux/Unix on 20th August 2006, 2:26 am by Stuart

Note: It is likely you will need root access to carry out apache config alterations

12-02-07: Fixed mistake in the directory comparison line.

If you want to be able to redirect blah.domain.com to domain.com/blah/ so that blah.domain.com is shown in the address bar here’s a quick and dirty how to:

First off if you want any subdomain to be able to be redirected first you need to set-up your DNS correctly. In my case this was as simple as going to the people that host my domain and adding an A record with the wildcard * that pointed to my server’s ip address. Bear in mind your DNS settings may take a while to work so be patient. Before you proceed you should check that anything.domain.com resolves to the ip address of your server. You can check this by running:

ping iloveapache.domain.com

This should respond with something like this:

[root@cheekymonkey conf]# ping iloveapache.domain.com
PING iloveapache.domain.com (62.193.xxx.xxx) 56(84) bytes of data.
64 bytes from my.serverhostame.com (62.193.xxx.xxx): icmp_seq=0 ttl=64 time=0.058 ms
64 bytes from my.serverhostame.com (62.193.xxx.xxx): icmp_seq=1 ttl=64 time=0.040 ms
64 bytes from my.serverhostame.com (62.193.xxx.xxx): icmp_seq=2 ttl=64 time=0.071 ms
64 bytes from my.serverhostame.com (62.193.xxx.xxx): icmp_seq=3 ttl=64 time=0.028 ms

The next step is to set-up the virtual host to respond to the wildcard subdomains. In the case of plesk you have to set-up a vhost.conf file but on any other apache installation you can just edit httpd.conf and look for the <VirtualHost> that corresponds to your site. If you are using Plesk you will need to ssh in to your server and create a vhost.conf file if it doesn’t already exist here where <domain.com> is your domain:

/var/www/vhosts/<domain.com>/conf/vhost.conf

Open that file with the command line editor of your choice and add the following directives:

ServerAlias *.domain.com
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.* [NC]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com
RewriteCond /var/www/vhosts/domain.com/httpdocs/%1 -d
RewriteRule ^(.*) /%1/$1 [L]

Substitute domain.com for your domain. Now here’s a quick walkthrough how these rules work. The first line ServerAlias *.domain.com tells apache to accept anysubdomain.domain.com.

Next the rewrite rules work as follows:

  1. The first line of mod_rewrite !^www.* only matches urls that don’t begin with www. You don’t want to redirect www.domain.com to www.domain.com/www/ do you? Note: you could add additional lines like these to prevent re-writing other subdomains like secure.domain.com if that should not be redirected to domain.com/secure/
  2. The second line ^([^\.]+)\.*$ captures into a backreference anything that doesn’t have a period e.g. the subdomain. The plus makes sure that there is at least one character that matches.
  3. The next condition checked is that the directory captured into the backreference does actually exist hence the -d.
  4. This last line ^(.*) /%1/$1 [L] takes the requested path and dumps it into a back reference and then rewrites it to point to the a directory (the subdomain backreference captured in the Rewrite conditions above) . In other words %1 is the subdomain backreference and $1 is the path backreference (that captured by .*). The important thing to rember is you can refer to backreferences in rewriteCond lines with % and backreferences in rewriteRules with $. Lastly the [L] (last) means doen’t further rewrite this URL. Note: You might want to leave this out if you are doing any subsequent rewrites, be sure to test what you have set-up thoroughly!!!

Now once you have made those changes if you are running plesk you will need to apply your vhost.conf changes with the following command:

/usr/local/psa/admin/sbin/websrvmng --reconfigure-vhost --vhost-name=<domain.com>

And then whether are using Plesk or not you need to restart apache e.g:

service httpd restart

Now you should find that if you set-up a directory called “meegan” with a valid index.html file in it. meegan.domain.com should find that file. The job’s a good’un.

Post Tools

Comments: Add yours

1. On August 20th, 2006 at 2:05 pm Tim Huegdon said:

I love that. You ask your mate a question and what does he do? He blogs it… and with your wife’s name as one of the examples!

Cheers buddy. ;)

2. On August 23rd, 2006 at 5:36 am warren said:

ah – just what I was looking for! thnx…

one thing – I am trying to rewrite to http://www.domain.com/red/subdomain — what would be change for that? just adding in “/red/” doesnt seem to work

3. On August 23rd, 2006 at 8:55 am Stuart Colville said:

@Warren: If you want to do that try this:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.* [NC]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com
RewriteCond /var/www/vhosts/domain.com/httpdocs/red/%1 -d
RewriteRule ^(.*) /red/%1/$1 [L]

Perhaps you missed out the second line which checks that the directory exists?

4. On August 23rd, 2006 at 10:48 am Satya said:

Hi,

I have a site, http://www.hrindian.com. Instead of http://www.hrindian.com, i can even type blogs.hrindian.com. It all goes to the server main page, that is /welcome.php
Now I want to re-direct blogs.hrindian.com/anything to /blogs/blogsothers/blogs.php?id=anything

So if we type, http://blogs.hrindian.com/satya, then it should be redirect to http://www.hrindian.com/blogs/blogsothers/blogs.php?id=satya

Can you help me with this. The apache server is hosted on the linux system.

Satya

5. On August 24th, 2006 at 4:30 pm Nico said:

Nice stuff, I would like to add www. to my subdomains as well. So http://www.domain.com should still go to the root, but http://www.sub.domain.com should go to the sub dir.
How to do this?

6. On September 4th, 2006 at 5:07 pm oosman said:

Thank you for these instructions.

You can also do this using virutal hosts, but I did not know about this method.

To do it using virtual host method add new virtual host in http.conf file:

pico -w /etc/httpd/conf/httpd.conf

then add this block:

ServerName bugzilla.demha.com
ServerAlias bugzilla.demha.com
ServerPath /bugzilla
DocumentRoot /var/www/html/bugzilla
DirectoryIndex index.shtml index.html index.php index.htm

However this does not work for secure apache (https) – that is why your method is helpful. However I the pages now served from the sub-directory are no longer encyrpted. I am trying to figure out how to encrypt the sub-domain pages as well.

7. On September 22nd, 2006 at 9:05 am Jim Callender said:

This is the way to do it on apache. But why not save less code and use .htaccess?

All you have to do is in file name “.htaccess” put in file:

DirectoryIndex about.htm

then your website address: http://www.website.com/about/

will go to: http://www.website.com/about/about.htm

without this file you will either get a 404 or view the parent directory.

Hope this helps those who dont dabble in apache :)

8. On October 31st, 2006 at 10:59 pm bdogg64 said:

Thanks a bunch!

9. On February 6th, 2007 at 9:17 pm Gijsbert said:

First of all great explanation. I’m trying to rewrite a cname.domain.com to domain.com/dir/cname.php

With the explanation above I can rewrite:

cname.domain.com –> domain.com/dir/cname/

But I need cname as being a php-file, so it should be:

cname.domain.com –> domain.com/dir/cname.php

Any ideas?

10. On February 23rd, 2007 at 3:31 pm Joey B said:

This is exactly what I have been looking for. My only question is that I don’t have a domain assigned to my server (yet) and I need to know if there is a way to make the rewrite the computer with the name it was called by instead of a domain name. So no matter what the server is called by (127.0.0.1,localhost,192.168..,Computer name, domain name) it returns that name.

11. On March 6th, 2007 at 2:23 pm Tim said:

Help..! I tried setting up the above method, but through Plesk dns zones instead of my registrar. Well plesk sucks in my personal feeling when it comes to managing DNS and subdomains.

MY main web site is fine but my subdomains are hit and miss. How do you setup your zone files through your registrar and point to plesk without conflicts? I can manage my registrar no problems but when I activate them there is nothing. Do you change or turn off plesk dns?

12. On June 1st, 2007 at 4:26 am Charles said:

I have a mod rewrite problem that I cannot find a solution to. So, if anyone is interested in solving this for a high school teacher, here it is.

I have the following .htaccess file in my root directory for http://www.myedusite.com

RewriteCond %{HTTP_HOST} ^([^.]+)\.k12\.myedusite\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteCond %{REQUEST_URI) !^%1/ [NC]
RewriteRule ^(.*)$ /home/httpd/vhosts/myedusite.com/httpdocs/webumake/teachers/%1/$1

This rewrite creates http://username.k12.myedusite.com, so my website of http://chills.k12.myedusite.com will read exactly the same in the url address. I have a subdomain program installed in the web site builder that does this for any username account.

The question I have is how do I change the rewrite so that anyone who types in http://chills.k12.myedusite.com will be redirected to https://chills.k12.myedusite.com?

Sincerely,
Charles

13. On April 16th, 2008 at 3:24 am Brad said:

How would one do this with say WAMP Server?

14. On July 13th, 2008 at 6:42 am Alex said:

Does anybody know how to set it up on a server running CPanel? Tried with virtual hosts method and my apache process is 190Mb in size…
Filesland

15. On April 7th, 2009 at 8:48 pm meegan said:

So random that I was looking to figure how to do this and he used my name! Too funny. Good article and especially awesome use of my name : )

16. On October 22nd, 2009 at 1:24 pm Pieter said:

Thanks! Works perfect!

17. On November 9th, 2009 at 6:42 am vijay said:

I have One issue, please help me. My issue is I have url http://subdomain.mydomain.com and want to redirect them http://mydomin.com/folder1/index.php?user=subdomain. but I dont want to change URL in addressbar so in addressbar the url should be http://subdomain.mydomain.com. What i have to do? My .htaccess code is:

=================================
#RewriteCond %{HTTP_HOST} !^www\.mydomain.com [NC]
#RewriteCond %{HTTP_HOST} ([^.]+)\.mydomain.com [NC]
#RewriteRule ^(.*)$ http://mydomain.com/folder1/index.php?user=%1 [L]
=================================

It redirect correctly, But Unfortunitly, it affect addressbar, so it’s useless for me. Please help me. What I have to do? Thanks in advance.

18. On December 2nd, 2009 at 7:01 pm Bruno said:

hello..
i’ve tried

ServerAlias *.ingrupo.com
RewriteEngine on

RewriteCond %{HTTP_HOST} !^www.* [NC]
RewriteCond %{HTTP_HOST} !^webmail.* [NC]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.ingrupo\.com
RewriteCond /var/www/vhosts/ingrupo.com/httpdocs/sites/%1 -d
RewriteRule ^(.*) /sites/%1/$1 [L]

and it redirects ok.. but webmail doesnt work.. it redirects to ingrupo.com and not for the real webmail.ingrupo.com
any ideas?!

Regards,
B

19. On December 3rd, 2009 at 9:37 am Stuart Colville said:

@Bruno: The second RewriteCond directive is saying ensure the host does not start with webmail.

As a result any requests to webmail.ingrupo.com will not be processed by the rest of the re-write rule.

20. On December 3rd, 2009 at 10:45 am Bruno said:

Hello…
perhaps i didnt explain the way it should :)
i want that webmail.ingrupo.com goes to webmail ( HORDE ) the default server webmail reader and not a directory inside ingrupo.com.
if i remove that line it will search for that dir inside ingrupo.com/sites right? but i want that when users type webmail.ingrupo.com they can access the email software from that server.

Regards,
B

21. On January 30th, 2010 at 7:51 am emre said:

hey there,

i am looking for a way to internally redirect http://xxx.domain.com/yyy requests to file.php?item1=$xxx&item2=yyy on apache.

namely i need a subdomain and an ordinary redirect at the same time.

i can do http://xxx.domain.com > somefile.php?item=xxx and http://www.domain.com/yyy redirects seperately. now i need to combine them.

i tried this:
RewriteCond %{HTTP_HOST} !^www\.ceviritercume\.org$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.ceviritercume\.org/([A-Za-z0-9_)(:!-',]+)/?$ [NC]
RewriteRule ^$ /dil_konu.php?dil=%2&konu=$1 [L]

but no success…

any ideas how it can be achieved?

22. On February 3rd, 2010 at 8:05 am Adam Klein said:

Glad to find this post.

I’d like to redirect advisors.pacificadvisors.com to http://thedock.pacificadvisors.com/advisors/training-education-schedule
using vhost.conf as I tried .htaccess and that didn’t work. Currently vhost.conf file has:

serverAlias *.domain.com
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.* [NC]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com
RewriteCond /var/www/vhosts/domain.com/httpdocs/%1 -d

would appreciate some help
RewriteRule ^(.*) /%1/$1 [L]







XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Using Loggerhead with mod_wsgi|(0)

Here’s a post I wrote over on the Project Fondue Blog about our use of Loggerhead with mod_wsgi under Apache. Loggerhead is the rather nice branch viewer for bazaar branches as used on Launchpad.net.

If you’re not already subscribed to the Project Fondue blog feed then I can recommend it, as there should be some interesting posts coming out of there in the coming months (yes I’m unashamedly biased!).

Ubuntu: Turn off changing workspace with mouse wheel|(1)

I found the changing with the workspace with the mouse wheel really annoying. To disable it go to System => Preferences => CompizConfig (available if the compizconfig-settings-manager package is installed) and uncheck “Viewport Switcher” which is under the “Desktop” heading.

Photos on Flickr

© Copyright 2004-10 Stuart Colville, all rights reserved. May contain traces of Muffin. Powered by WordPress. Hosting by Slicehost.com This page was baked in 0.608s.