Search code examples
regex.htaccessurl-rewritingapache2

.htaccess rewrite


I don't know if this is the right area, but here goes:

I have a RewriteRule

RewriteRule ^(eScience/)?(\w+)/RENDER/(\d+)/(\d+)/P(\d+)\.html$ /RENDER/escience/kids/1016/2063/test.html [L,NC]

that works fine because I've hardcoded the IDs in. Now when I do something like

RewriteRule ^(eScience/)?(\w+)/RENDER/(\d+)/(\d+)/P(\d+)\.html$ /RENDER/escience/kids/$2/2063/test.html [L,NC]

The rewrite doesn't work, I get page not found. The really odd part is that $4 works, so if I do something like

RewriteRule ^(eScience/)?(\w+)/RENDER/(\d+)/(\d+)/P(\d+)\.html$ /RENDER/escience/kids/1016/$4/test.html [L,NC]

it works, but anything 3 and under doesn't work. Any ideas? The URL that I am using is http://www.escience.ca/kids/RENDER/1016/2063/P2063.html

As you can see, $3 and $4 are the exact same IDs, so that's why my third example works.


Solution

  • Look at your regex groups:

    RewriteRule ^(eScience/)?(\w+)/RENDER/(\d+)/(\d+)/P(\d+)\.html$ /RENDER/escience/kids/$2/2063/test.html [L,NC]
                 $1          $2           $3    $4     $5
    

    It should be obvious why it doesn't work - $2 is not the number you expected. Maybe you should use named groups for complex regular expressions if you loose track of the numbering. You can exclude regex groups from being grouped by using the ?: operator, by the way (for example "(?:ungrouped)(dollar1)(dollar2)").