3

I am using the following code to redirect wildcard subdomains (*.domain.com) to their coresponding folder in /users and redirect direct requests to the /users folder to the subdomain version:

Protect Direct Access to Wildcard Domain Folders:

RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^users/([a-z0-9\-_\.]+)/?(.*)$ http://$1.domain.com/$2 [QSA,NC,R,L]

Handle Wildcard Subdomain Requests:

RewriteCond %{REQUEST_URI} !^/users/ [NC]
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$ [NC]
RewriteCond %1 !=www [NC]
RewriteRule ^(.*)$ /users/%1/$1 [L]

This code works well enough, however there are two problems that I can't seem to fix.

  1. The below scenario seems to happen because there isn't a trailing slash on the requesting URI:

    username.domain.com/sub1 => username.domain.com/users/username/sub1 username.domain.com/sub1/ => username.domain.com/sub1/

  2. The users directory can still be accessed directly by using a subdomain:

    username.domain.com/users/username/sub1 => Works and shouldn't

I'm at a loss and would really appreciate if anyone has any ideas.

Thank you!

dSquared
  • 9,725
  • 5
  • 38
  • 54

1 Answers1

0

For the problem 2, I think your first protection rule just needs to redirect all subdomains. It's redirecting www, but lets username.domain.com come through as-is.

This will redirect any direct access request to the users path.

RewriteCond %{HTTP_HOST} ^.+\.domain\.com$ [NC]
RewriteRule ^users/([a-z0-9\-_\.]+)/?(.*)$ http://$1.domain.com/$2 [QSA,NC,R,L]

I think it can be a little simpler by just looking for any host ending in domain.com (which would even handle no subdomain, just domain.com) (I didn't test this....)

RewriteCond %{HTTP_HOST} domain\.com$ [NC]
RewriteRule ^users/([a-z0-9\-_\.]+)/?(.*)$ http://$1.domain.com/$2 [QSA,NC,R,L]

For problem 1, I'm stumped too, sorry. It's acting like the trailing slash is failing the rules, so it falls through as-is. But I would expect it to do as you want it to:

username.domain.com/sub1/ => username.domain.com/users/username/sub1/

Perhaps try the %{REQUEST_URI} tag, instead of trying to capture .*. I don't see the difference, but maybe it'll help.

RewriteCond %{REQUEST_URI} !^/users/ [NC]
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$ [NC]
RewriteCond %1 !=www [NC]
RewriteRule .* /users/%1%{REQUEST_URI} [L]
goodeye
  • 2,389
  • 6
  • 35
  • 68