.htaccess wildcard subdomain path

.htaccessapache-2.2subdomain

I have my site set up like this:

RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ([^.]+)\.example\.com [NC]
RewriteRule ^/?$ /user/profile.php?name=%1 [L]

What this does is if user visits: test.example.com, it will show contents of file: example.com/user/profile.php?name=test. If someone goes to lol.example.com, it will show page: example.com/user/profile.php?name=lol but the URL will remain the same with the subdomain, like test.example.com and lol.example.com.

That part is working.


Question:

If I go to test.example.com/login, it will show my domain root file. How can I make it so that it will show things from the /user folder?

For example:

  • test.example.com/login will show example.com/user/login and test.example.com/register will show example.com/user/register but the URL will remain the same with the subdomain?

  • test.example.com/pathtofile should get the contents of example.com/user/pathtofile. "pathtofile" should be dynamic. I just want the path to look in the folder /user, not the root folder.

Best Answer

if someone goes to lol.example.com, it will show page: example.com/user/profile.php?name=lol.

Strictly speaking, it will show the page: lol.example.com/user/profile.php?name=lol (the subdomain is not removed). But since (I assume) all the subdomains and main domain point to the same place on the filesystem, it works.

test.example.com/pathtofile should get the contents of example.com/user/pathtofile

Your original directive only rewrites a request for the document root (test.example.com/). To rewrite /pathtofile then you can add another rule block after the above in .htaccess. For example:

RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} [^.]+\.example\.com [NC]
RewriteCond %{REQUEST_URI} ^/([^/]+)$
RewriteRule !^user/ /user/%1 [L]

This rewrites all requests that don't already start /user/ and that consist of just a single (non-zero length) path segment, as in your example (eg. /pathtofile and not /path/to/file), and rewrites to /user/pathtofile.

UPDATE: If you have an ErrorDocument defined then you will need to make an exception earlier in your `.htaccess file to prevent subrequests for the error document from being rewritten. For example:

RewriteRule ^404\.php$ - [L]
Related Topic