I'm trying to host a site on which user profile pages come with unique subdomains, such as username.sitename.com. I would like an Apache/VirtualHost solution for pointing *.sitename.com to sitename.com/index.php, where I could assort, which subdomain comes with a profile page and which would show 404 error.
Please help me setting up the .htaccess
You need only a correct VirtualHost setup.
<VirtualHost *:80>
ServerName example.com
ServerAlias *.example.com
[...]
</VirtualHost>
As the index.php is in the DirectoryIndex it is called automatically, regardless which domain is called. Do dynamically react you have acces to the requested host trough the $_SERVER['HTTP_HOST']
variable.
It's best to do this with a 301 redirect at the server level in the httpd.conf file (or an included config file). Rather than creating a VirtualHost and making the server answer and filter with an .htaccess file for each domain, you can setup the redirect in the VirtualHost itself.
You can do this with mod_rewrite
<VirtualHost *>
ServerName subdomain.example.com
RewriteEngine on
RewriteRule ^/(.*)$ http://example.com/index.php [L,R=301]
</VirtualHost>
<VirtualHost *>
ServerName subdomain2.example.com
RewriteEngine on
RewriteRule ^/(.*)$ http://example.com/404.php [L,R=301]
</VirtualHost>
or if you're running mod_alias you can use this:
<VirtualHost *>
ServerName subdomain.example.com
Redirect 301 / http://example.com/index.php
</VirtualHost>
<VirtualHost *>
ServerName subdomain2.example.com
Redirect 301 / http://example.com/404.php
</VirtualHost>