mod_rewrite complexity problem

Tag: .htaccess , mod-rewrite , subdomain Author: afafggg Date: 2009-09-12

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 should localized to los angeles, etc...essentially rewritten to

  2. i want to allow users to create to pass their profiles to friends with ease...essentially rewritten to

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?

Best Answer

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 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 *

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


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.


Don’t use addslashes for MySQL. Better use mysql_real_escape_string.