Article content

Configuring Apache to work with wildcard subdomains

Configuring Apache to accept wilcard domains can be very useful. Having the wildcard domain go to a specific subdomain is even more so, so here's a short how to.

Step one is to set up your domain to accept wildcard domains. This is done by configuring the A record for your domain so that any hits to anything.yourdomain.com (and by anything, I mean *.yourdomain.com) go to the IP address you have assigned to your server. Permalink for this article http://mirror.magicode.org/content/Configuring_wildcard_subdomains_with_Apache

Step two is to configure Apache to accept *.yourdomain.com. This is typically done by editing httpd.conf like so:

  1. # this accepts any subdomain
  2. DocumentRoot /www/yourdomain
  3. ServerName www.yourdomain.com
  4. ServerAlias *.yourdomain.com
This text was originally written for http://blog.magicode.org

That's the easy part, and if all you want is point example.yourdomain.com to www.yourdomain.com (or any other subdomain to www.yourdomain.com for that matter), you're done.

If you want to take it a step further, so that example.yourdomain.com points to www.yourdomain.com/example, you need to use Apache's Rewrite engine. It's a tricky beast, but let's give it a go.

Here's how you do it:

  1. #Turn the RewriteEngine on.
  2. RewriteEngine On
  3. #Fetch the subdomain. This accepts any combination of words
  4. RewriteCond %{HTTP_HOST} ^([-a-z0-9]+)\.yourdomain.com$
  5. #Make sure the subdomain is not www, which we want to leave
  6. #alone. If you have more subdomains to exclude, use a pipe
  7. #(|) to separate them -- like www|mail|etc...
  8. RewriteCond %{1} !^(www)$
  9. #Verify that the directory exists before we rewrite
  10. RewriteCond /web/yourdomain/public_html/%1 -d
  11. #Finally, stop this from looping, which would kill
  12. #the user experience in five parsecs (joke)
  13. RewriteCond %{REQUEST_FILENAME} !^/web/yourdomain/public_html/
  14. #And finally, the rewrite
  15. RewriteRule (.*) /web/yourdomain/public_html/%1/$1
If you see this notice on any site other than magicode.org, it's probably been lifted without consent

All you have to do now is store the above in the file called .htaccess in the root of your public folder (or add it to the VirtualHost directive in httpd.conf) :).

Discussion

Submit your comment

Text:

Your name:

Your email:

Show my mailaddress (spam protected)

Your website:

Show my website

Featured Article

PHP Variables and strings

A variable is a means of storing a value, such as a text string or a number. In PHP you do not have to declare your variable, as it's automatically declared when you set it. Since you do not need to declare the variable, you do not have to specify what kind of data it contains either.

Topics
Magicode's own open source project
From the forum / Latest comments
You may also want to to check out these links: sendanonmail.com, superstrongpassword.com.