mod_rewrite: hierarchical sub-domains into hierarchical sub-directories
Consider the following problem, please. I have got domain.tld with hierarchical sub-domains like the following:
a.domain.tld
b.a.domain.tld
c.b.a.domain.tld
... etc.
There is also hypothetical directory structure in the web-root:
/foo
/a.
/a./b.
/a./b./bar
/a./b./c.
... etc.
I would like to achieve such rewrite that would cause Apache to serve directories in a way you see below.
a.do开发者_如何转开发main.tld --> /a.
b.a.domain.tld --> /a./b.
c.b.a.domain.tld --> /a./b./c.
... etc.
Directories without trailing dot character would behave as normal sub-directories.
domain.tld/foo/ --> /foo
a.b.domain.tld/bar --> /a./b./bar
I can not use mod_vhost_alias and would be glad if the solution was achievable using mod_rewrite only. Is it possible to achieve such rewrite?
Thank's for all your advices.
--
nkdPossible solution for 4 levels of sub-domains:
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.tld
RewriteRule (.*) %1./$1 [R,L]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.domain\.tld
RewriteRule (.*) %2./%1./$1 [R,L]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.([^\.]+)\.domain\.tld
RewriteRule (.*) %3./%2./%1./$1 [R,L]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)\.domain\.tld
RewriteRule (.*) %4./%3./%2./%1./$1 [R,L]
Thank you.
--
nkd
The previous solution ends in very funny infinite redirect loop. Here's a solution I got now (not very elegant, but it works; but with a huge 'but'):
# Working solution for five levels of sub-domains
RewriteEngine on
RewriteCond %{HTTP_HOST} ^([^\.]+)\.DOMAIN\.TLD [NC,OR]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.DOMAIN\.TLD [NC,OR]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.([^\.]+)\.DOMAIN\.TLD [NC,OR]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)\.DOMAIN\.TLD [NC,OR]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)\.([^\.]+)\.DOMAIN\.TLD [NC]
RewriteRule (.*) http://DOMAIN.TLD/%5./%4./%3./%2./%1./$1 [R,L]
Can somebody explain to me why (the hell) it works? It really does work, I tested it extensively. But why does it work actually? If I look at the RewriteRule line I doubt it should work... Thank you for your explanations.
BTW: If the above five rewrite conditions and rule work, it looks like it could be re-written in some sort of 'two-liner' (one condition plus one rule). I tried that already, by using the above rule and the following condition instead of the five conditions given above:
RewriteCond %{HTTP_HOST} ^(([^\.]+)\.)+DOMAIN\.TLD [NC]
and played with it a little but with no real success. Thanks for all ideas how to simplify the rewrite stuff and make it more 'sane' (if possible).
--
nkd
It is possible if you send the part to be reversed to an external script via RewriteMap
and have that handle it.
精彩评论