Dynamic subdomains cause problems with AJAX interactions

Hello everyone.

I currently have a bit of mod rewrite code in my rewrite.conf file to allow for dynamic subdomains. By dynamic sub domains, I mean http://username.mydomain.com ends up going to http://www.mydomain.com/viewprofile.php?username=username

Here’s the code to do this:


RewriteCond %{HTTP_HOST} !^www\\.paperdemon\\.com
RewriteCond %{HTTP_HOST} (.+)\\.paperdemon\\.com
RewriteCond %{QUERY_STRING} !^username=.
RewriteRule ^(.*)$ /profileview.php?username=%1 [L]

It’s a great feature. However, it redirects ALL traffic from any file on your subdomain. For example, http://user.mysite.com/format.css actually rewrites to http://user.mysite.com/ which rewrites to www.mysite.com/profileview.php?username=user.

As you can imagine, this can cause problems for images, css, js, and ajax calls. In order to counter this, I have to one of two things:
A) change all the src in my html to be prepended with http://www.mysite.com/ which works fine for css and images. or
B) black list that file/folder in the Rewrite Conditions. For example, if you’re on user.mydomain.com and there’s an AJAX call to /chatbox/display.php, I have to add the folder /chatbox/ to a black list in my rewrite.conf file. Like so:

RewriteCond %{HTTP_HOST} !^www\\.paperdemon\\.com
RewriteCond %{HTTP_HOST} (.+)\\.paperdemon\\.com
[B]RewriteCond %{REQUEST_URI} !^/chatbox/.*$[/B]
RewriteCond %{QUERY_STRING} !^username=.
RewriteRule ^(.*)$ /profileview.php?username=%1 [L]

I was wondering if there was a more elegant solution to this problem which would only capture and do a mod rewrite for user.mysite.com/ and not any subpages like user.mysite.com/file.php so that if user.mysite.com/file.php were accessed, it would actually go to www.mysite.com/file.php without the browser knowing.

If you have a better mod rewrite for dynamic sub domains I’d love to hear about it! Thanks so much!

If you’re looking to blacklist real directories, you can use !-d


RewriteCond %{SCRIPT_FILENAME} !-d

Instead of your


RewriteCond %{REQUEST_URI} !^/chatbox/.*$

If they are not real directories (ie passed through an MVC controller), you’re stuck with your method, as Apache doesn’t know which fake directories you’re app has created / is using.