Apache – Troubleshooting .htaccess Wildcard Subdomain Rewrite

.htaccessmod-rewrite

I have been working on this problem for a 3 solid days and posted on several forums with no leads.

Problem:

When a user types in SUBDOMAIN.domain.com I want it to stay that way in the URL window.

The real location of these files is domain.com/apps/SUBDOMAIN

I know that this is possible using a .domain.com DNS A record (which I have done) and a .htaccess rule.

This is my .htaccess rule at the moment

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+)\.domain\.com$ [NC]
RewriteRule !^([a-z0-9-]+)($|/) /apps/%2%{REQUEST_URI} [PT,L]

Ok, this almost works.

Typing in subdomain.domain.com is reading from domain.com/apps/subdomain

BUT something is going horribly wrong.

Visiting subdomain.domain.com/image.jpg (AKA domain.com/apps/subdomain) works fine

Visiting subdomain.domain.com/anyfolder/image.jpg (AKA domain.com/apps/subdomain) returns a 404

Looking at the Cpanel Error log shows this

[Thu Nov 18 20:48:50 2010] [error] [client ***.**.***.***] File does not exist: /home/domain/public_html/images, referer: http://subdomain.domain.com/apps/subdomain/

So it appears to be correctly rewriting on a first directory basis but anything lower then that gets sent back to public_html root

All help and advice would be greatly appreciated

Thanks,

Tim

PS. I had to remove the proper hyperlink formatting as I am a new user.

Best Answer

Correct me if I'm wrong, but the rewrite rule you have:

RewriteRule !^([a-z0-9-]+)($|/) /apps/%2%{REQUEST_URI} [PT,L]

says: rewrite only if ^([a-z0-9-]+)($|/) does not match. When your URL path is /anyfolder/image.jpg, the above will match (^anyfolder/), thus rewrite rule will not be run, so you will basically continue to subdomain.domain.com/anyfolder/image.jpg.

The following SO question has a similar requirement:

In his answer, glavić gives the response that should work, also gives this link:

Try it out, it should work OK.