James Crisp

Software dev, tech, mind hacks and the occasional personal bit

Percent Number in Apache Rewrite Rules (mod_rewrite)

What do the %1 %2 in a Rewrite rule mean? The Apache guide does not help, nor does any other documentation I found. I came across the %1, %2 etc in some complex and arcane rules. Google ignores percent signs, which makes it hard to get an easy answer.

We’ll use the rules from my last post as an example.

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([a-z.]+)$ [NC]
RewriteRule ^/(.*)$ http://www.%1/$1 [R=301,L]

The %1 refers to the capture group in a previous RewriteCond. This differentiates it from the $1 which refers to a capture group in the current RewriteRule.

Hopefully I have littered this post with enough keywords that future googlers will find the answer to the %1 %2 in ReWrite rules more easily 🙂

Previous

Adding WWW to domains, and Apache Rewrite Rules (mod_rewrite)

Next

Presentation Zen by Garr Reynolds

6 Comments

  1. To further help the keywords and the lost and lonely Web searcher, those numbers are called backreferences. Their use in mod_rewrite are described in the Apache manual.

  2. Ack, that <code> block was meant to be an inline element. Any chance of a “preview comment” feature?

  3. Thanks Rob, that Apache mod_rewrite manual reference is handy.
    James

  4. What makes it confusing is you 1) you can reference two different sets of backreferences, and 2) every regex implementation uses a different syntax for backreferences. It’s little wonder there’s over 1000 questions tagged mod_rewrite on stackoverflow.com.

  5. Thank you very much for taking the time to write this. Specially saying spelling it out to get caught by google.

  6. fdeel

    This code I get from the webhosting maintenance.

    RewriteCond %{HTTP_HOST} ^(.*)google.com$ [NC]
    RewriteRule (.*) http://cfshop.nl/?s=google [R=301,L]

    How do I read this code in my program with C#.net and wat is the read or write
    with kind regards.

Comments are closed.

Powered by WordPress & Theme by Anders Norén