views:

36

answers:

1

I have a need to mod-rewrite my domain based off of subdomains...there are two scenarios in which i would need to do this:

  1. my site is located in different cities...so losangeles.example.com should localized to los angeles, etc...essentially rewritten to www.example.com/?loc=losangeles

  2. i want to allow users to create username.example.com to pass their profiles to friends with ease...essentially rewritten to www.example.com/user.php?id=username

As my site scales, I plan on having over 300 locations, and several thousand users...which means that hand coding each rewrite rule would be a little tedious.

How can I tell mod-rewrite to decipher between a location subdomain and a username subdomain?

+2  A: 

I think fundamentally you need to rethink that strategy as mixing your namespaces is going to cause a lot of headaches in the long term. Consider what happens if you have missed out a city name, such as alexandra.example.com but a user has registered that username? Also, you are going to end up with having to do things like checking whether a city exists at the point that a username is trying to be created.

If you really do want to stick with this, one possibility is simply to send the requests to a single point which then does the lookup against your two databases and then internally sets a variable of either $city or $user .

Once you have set up your DNS wildcarding, in Apache set:

ServerAlias *.example.com

and then the rest of your virtualHost as normal.

Then in the application just check against $_SERVER['SERVER_NAME'], e.g.

$server_name = addslashes($_SERVER['SERVER_NAME']);    
$query = "select * from instances where '{$server_name}' regexp replace(concat(server, '$'),'.','\.') limit 1";

but then you're actually going to have to have two queries and additional logic to pull apart the two namespaces or handle clash situations.

I would use a namespace like

<cityname>.example.com/user/<username>

which will avoid the problems, and also mean that you can customise what is visible on the user's homepage depending on which city you've entered, if that is desirable.

fooquency
Don’t use `addslashes` for MySQL. Better use `mysql_real_escape_string`.
Gumbo