Use subpath internal proxy for subdomains, but redirect external clients if they ask for that subpath?

Posted by HostileFork on Server Fault See other posts from Server Fault or by HostileFork
Published on 2013-10-19T20:12:23Z Indexed on 2013/10/19 21:58 UTC
Read the original article Hit count: 279

I have a VirtualHost that I'd like to have several subdomains on. (For the sake of clarity, let's say my domain is example.com and I'm just trying to get started by making foo.example.com work, and build from there.)

The simplest way I found for a subdomain to work non-invasively with the framework I have was to proxy to a sub-path via mod_rewrite. Thus paths would appear in the client's URL bar as http://foo.example.com/(whatever) while they'd actually be served http://foo.example.com/foo/(whatever) under the hood.

I've managed to do that inside my VirtualHost config file like this:

ServerAlias *.example.com

RewriteEngine on

RewriteCond %{HTTP_HOST} ^foo\.example\.com [NC]   # <---
RewriteCond %{REQUEST_URI} !^/foo/.*$ [NC]         # AND is implicit with above
RewriteRule ^/(.*)$ /foo/$1 [PT]

(Note: It was surprisingly hard to find that particular working combination. Specifically, the [PT] seemed to be necessary on the RewriteRule. I could not get it to work with examples I saw elsewhere like [L] or trying just [P]. It would either not show anything or get in loops. Also some browsers seemed to cache the response pages for the bad loops once they got one... a page reload after fixing it wouldn't show it was working! Feedback welcome—in any case—if this part can be done better.)

Now I'd like to make what http://foo.example.com/foo/(whatever) provides depend on who asked. If the request came from outside, I'd like the client to be permanently redirected by Apache so they get the URL http://foo.example.com/(whatever) in their browser. If it came internally from the mod_rewrite, I want the request to be handled by the web framework...which is unaware of subdomains.

Is something like that possible?

© Server Fault or respective owner

Related posts about apache2

Related posts about mod-rewrite