2

I am building a download site, An users will be able to register and a folder with their username will be created on my server, something like: home/users/username

What I want to accomplish is, if anyone types: username.domain.com in their browser, it will route them to: home/users/username/, and if they type: username.domain.com/file.mp3, it will route them to: home/users/username/file.mp3

If its possible to accomplish sub folders routing, that would be great full aswell, example; home/users/username/sub/file.mp3

Thanks guys

Ulrich Palha
  • 9,411
  • 3
  • 25
  • 31
code4_days
  • 27
  • 3

2 Answers2

2

Try adding the following to the .htaccess file in the root directory of your site.

This will rewrite any request to username.domain.com to the correct folder/subfolder and file.

I am assuming that home is a directory in the root folder of your site.

RewriteEngine on
RewriteBase / 

#if request for usename.domain.com/anything
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com$ [NC] 
#send any request that is not already for home/users to home/users/username/anything
RewriteRule ^(?!home/users/) home/users/%1%{REQUEST_URI} [L,NC] 
Ulrich Palha
  • 9,411
  • 3
  • 25
  • 31
  • I have one issue with it, whenever I type: test.domain.com/folder without a trailing slash, it shows the real path of the folder in the url: test.domain.com/home/users/test – code4_days Feb 23 '12 at 04:14
  • @user1209681 Try adding `DirectorySlash Off` before `RewriteEngine On`, but see caveats http://stackoverflow.com/questions/3258879/apache-directoryslash-off-site-breaks – Ulrich Palha Feb 23 '12 at 15:29
  • works perfect @Ulrich Palha thanks. One more question, is there any other way I can do this without using .htaccess ? Initially, which ever way will work out best, performance wise, under high traffic volume. – code4_days Feb 23 '12 at 17:37
  • @user1209681 You could also do this in your virtual host (if you have access to it). Syntax is slightly different, performance difference better, but probably imperceptible – Ulrich Palha Feb 23 '12 at 20:29
0

I tried what Ulrich Palha recommended but no luck. I hope this will help guys like me where Ulrich's answer doesn't work.

# Rewrite username.domain.com/<path> to domain.com/home/username/<path>
#
# Rewrite only if not already rewritten to /home/
RewriteCond $1 !home/
# Skip rewrite if subdomain is www
RewriteCond %{HTTP_HOST} !^www\. [NC]
# Extract (required) subdomain to %1
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com$
# Rewrite to /home/username/URL-path
RewriteRule (.*) /home/%1/$1 [L]
BeRocket
  • 655
  • 4
  • 12