Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

how to make more complex and dynamic rewrites using $1, %1, %2 etc.

I'm trying to make a more dynamic rewrite (got a lot of domians pointing to the same server/site)

#   put 'www' as subdomain if none is given
RewriteCond %{HTTP_HOST}        ^([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^(.*)$          http://www.%1/$1 [L,R=301]

#   rewrite subdomains
RewriteCond %{HTTP_HOST}        ^(admin|files|imap|mysql)\.[^\.]+\.[^\.]+$ [NC]
RewriteCond %{REQUEST_URI}      !^/_(admin|files|imap|mysql)/ [NC]
RewriteRule ^(.*)$          /_%1/$1 [L]

#   redirect to subdomain
RewriteCond %{HTTP_HOST}        ^www\.([^\.]+\.[^\.]+)$ [NC]
RewriteCond %{REQUEST_URI}      ^/_([^/]*)/ [NC]
RewriteRule ^(.*)$          http://%1.domain.com/ [L,R=301]

#   rewrite 'secure' subdomain
RewriteCond %{HTTP_HOST}        ^(demo|secure)\.[^\.]+\.[^\.]+$ [NC]
RewriteCond %{REQUEST_URI}      !^/_secure/ [NC]
RewriteRule ^(.*)$          /_secure/$1 [L]

but now I'm confronting a problem..

by #redirect to subdomain I can't figure out how to solve the condition and rule like the other I have made.. somehow I need to extract the domain from the first condition and then use it in the rule with %1, but how can you do that when you got another condition in between?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

The capture data for %1 etc is used from the RewriteCond immediately above the RewriteRule.

Is there any reason your URI path evaluation/capture can't just occur in the RewriteRule? Something like this (I think this is what you're going for?):

RewriteCond %{HTTP_HOST}        ^www\.([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^/_([^/]*)/$        http://$1.%1/ [L,R=301]
share|improve this answer
    
now it doesn't redirect.. –  clarkk May 25 '11 at 15:36
    
if I change the rewrite rule with this to test it it doesn't work.. RewriteRule ^/_ google.com [L,R=301] –  clarkk May 25 '11 at 20:40
    
got it :) RewriteRule ^_([^/]+)/ http://$1.%1/ [L,R=301] –  clarkk May 25 '11 at 21:28
    
@clarkk That's the context sensitivity of RewriteRule at work - My config assumed they were just in a VirtualHost block, where absolute paths are used, but when they're in a Directory block or .htaccess file, the relative path is used. –  Shane Madden May 26 '11 at 0:34
    
but thanks.... :) –  clarkk May 26 '11 at 6:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.