user24601 user24601 - 2 months ago 6
Apache Configuration Question

Trouble redirecting sub.example.com to sub.example.com/directory/

I have a website set up at example.com/directory/ currently. /directory/ is set up to display different contents depending on the subdomain, that part is working fine. I'm having trouble editing my httpd.conf file to work correctly though.

Obviously I can only set up my A records for sub.example.com to point to example.com and not example.com/directory/ so I've set up some rules in my httpd to get around this, but they don't seem to be working. This is what I've got so far:

RewriteCond %{HTTP_HOST} ^sub1\.example\.com$ [NC]
RewriteRule ^((?!directory).*)$ /directory/$1 [NC,L]

RewriteCond %{HTTP_HOST} ^sub2\.example\.com$ [NC]
RewriteRule ^((?!directory).*)$ /directory/$1 [NC,L]


What seems to be happening though is those rules just direct each subdomain to example.com/directory and drop the subdomain completely. I'm a little lost as to what I need to change here, I'm not very well versed in Apache.

I know this should be simple, but I can't seem to find any documentation that is straightforward enough for me to understand, does anybody have any pointers?

Answer

You should be using separate sub-directories for each subdomain like this:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^sub1\.example\.com$ [NC]
RewriteRule ^((?!folder1/).*)$ folder1/$1 [NC,L]

RewriteCond %{HTTP_HOST} ^sub2\.example\.com$ [NC]
RewriteRule ^((?!folder2/).*)$ folder2/$1 [NC,L]

Where folder1 is sub-directory for sub1 domain and folder2 is sub-directory for sub2 domain.