I'd like to add a rule so that all subdomains get redirected to a subfolder. For example:
app1.example.com -> example.com/app1
app2.example.com -> example.com/app2
something.example.com -> example.com/something
All subdomains will only be one level deep.
Questions
- Which DNS providers allow me to do this?
- Are these alternatives feasible?
- Redirect them all to a special webapp with a static IP that redirects to the proper subfolder. How can I know from which subdomain they came from?
- Programatically create each rule when I need it. Which DNS providers have API access to add rules? I think Amazon Route 53 might be the answer here.
Best Answer
All competent ones. It doesn't even need to be a DNS-specific providing, most good hosts will help you with this too. There are two stages:
*.example.com
*.example.com
by routing it toexample.com
'sVirtualHost
.Then, at your end, you add a
.htaccess
entry that uses aRewriteRule
to catch each subdomain, and redirect it to a folder using theHTTP_HOST
variable.Untested, but something like this:
Suppose that the user requests
app1.example.com/bob
.Line 2
This will catch
app1.example.com
in theHTTP_HOST
- it'll match theRewriteCond
.Line 3
Normally, Apache will only pass
/bob
to be checked against theRewriteRule
. To use the subdomain, we exploit Chaining by forcing the next rule to matchLine 4
The final
RewriteRule
is now matching againstapp1.example.com/bob
and not just/bob
. As a result, it can have a 'full' regular expression to match both this subdomain and the path, and perform the desired redirect.If you don't want this feature, you can simplify the rules.
There is no sure-fire way of doing this. You could try the HTTP Referer, but it's not always sent by all browsers, some firewalls remove the header, etc.
This would actually result in a more complex solution to the above, so I wouldn't recommend it. It would also create a delay: DNS caches would need to update and certain visitors wouldn't be able to use the subdomain immediately until they do. At least with my suggestion above, they'd be able to get going instantly.