Apache mod_rewrite: one RewriteCond to many RewriteRules

Today I decided to resolve a problem in an Apache virtual container rewrites I’d been having for a while. It appeared that RewriteCond was “leaking”.  However, on closer observation (and lots of Googling) it turned out that RewriteCond only applies one RewriteRule that comes immediately after the RewriteCond. I didn’t know that (or I had forgotten it). Either way, it didn’t seem like such a great idea to have to duplicate a lengthy RewriteCond definition half a dozen times for multiple RewriteRules in each group which there are ten (that would’ve been almost hundred duplications – not fun to maintain when the rules change).

Turns out there is a fairly simple trick to achieve exactly what I was looking for: if the RewriteCond is negated and followed by RewriteRule . – [S=n] to skip following n rules, the RewriteRules in essence are only applied when the singular RewriteCond is true. Like so:

RewriteCond %{REQUEST_URI} !^/(pattern1|pattern2|pattern3)(/[0-9]+|/P[0-9]+|)[/]?$ [NC]
RewriteRule . - [S=3]
RewriteRule ^/([^/]*)[/]?$ /index.php/site_embeds/department/$1/X [L]
RewriteRule ^/([^/]*)/([0-9]+)[/]?$ /index.php/site_embeds/article/$2/$1 [L]
RewriteRule ^/([^/]*)/P([0-9]+)[/]?$ /index.php/site_embeds/department_archive/P$2/$1 [L]

Now the last three rules are skipped if the condition is not true or, in reverse: they are applied if the condition is true. In other words, exactly what I was looking for!