Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ^(.*)$ [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
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 ^/_ [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


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.