Question

I wan't people to be able to register their own sections within my site, and have those sections be their own subdomain of my site. so someone can register 'test' and have 'test.example.com' refer to their site which would be at say /site.php?id=1 So how would i go about writing a mod_rewrite rule for this?

Was it helpful?

Solution

mod_rewrite might not be the best tool for this. RewriteRules are great for mapping a file to something else, but it was not really meant for domain matching.

The best you can do using mod_rewrite is the following:

RewriteEngine On
# Skip www.domain.com
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com
RewriteRule ^/(.*)$  site.php?domain=%1&file=$1 [L]

Which is not really useful. What I would recommend to do instead if programmatically check the value of HTTP_HOST as such:

function get_subdomain() {
  if(preg_match('/^([^.]+)\.domain\.com/i', $_SERVER['HTTP_HOST'], $matches)) 
    return $matches[1];
}

OTHER TIPS

You can configure apache to claim the "special" domains in the apache configuration (e.g. www.mydomain.com, etc), in your virtual host containers and have the others default to your first virtual host. You can then rewrite the base url to a dispatch application that inspects the URL and sends the user off to their correct area.

From Apache 2.0 docs:

Almost any Apache directive may go into a VirtualHost container. The first VirtualHost section is used for requests without a known server name.

Put the code to handle *.mydomain.com in the first virtual host:

<VirtualHost *:80>
  Servername custom.mydomain.com
  DocumentRoot /var/www/html/custom
  RewriteEngine on
  RewriteRule ^/$ /var/www/cgi-bin/dispatch.cgi [R]
  # more configs here
</VirtualHost>

<VirtualHost *:80>
  Servername www.mydomain.com
  DocumentRoot /var/www/html/homepage
  # more configs here
</VirtualHost>

In dispatch.cgi, inspect the calling url to determine where the user should go. Make sure you set up your DNS to accept all subdomains.

Hope that helps!

Actually, we've been using this technique without much problem for the past year. Our mod_rewrite config looks like:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !www.mydomain.com
RewriteCond %{HTTP_HOST} ^([^.]+)\.mydomain\.com
RewriteCond %{REQUEST_URI} !admin
RewriteRule (.*) /admin/ [R=301,L]
RewriteRule ^admin(.*)$ hosted/admin/$1 [QSA,L]

What happens, is that users are directed to theiraccount.mydomain.com/admin.

We then use PHP to identify the account portion of the domain name. Using something like $_SERVER['SERVER_NAME'] or some method of getting the domain name and parsing it works very well.

Keep these configs in the httpd.conf though, this will become a cpu problem in higher traffic sites if it's kept as .htaccess.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top