Skip to content

.htaccess - one RewriteCond for many rules

Sometimes you need many RewriteRule lines, each preceded by a RewriteCond condition, so your .htaccess grows by twice as many lines - what if you could use just one RewriteCond?

Let me say right away that it is neither safer nor more convenient (if you want to change anything later), but it does open some new possibilities 😉

One Ring to rule them all, One Ring to find them,
One Ring to bring them all and in the darkness bind them

from the Ring verse, J.R.R. Tolkien

S for "Skip"

Rules can end with one or more flags that pass extra instructions to the parser. One of them is [S], "skip", where after the letter you give the number of rules to skip, e.g. [S=5].

Hold on! We don't want to skip anything, quite the opposite!

Right. That is why we skip the following rules when they do not meet the RewriteCond condition, by putting an exclamation mark "!" before the expression:

RewriteCond %{QUERY_STRING} !colour=transparent
RewriteRule .? - [S=3]
RewriteRule ^pack-1$ /pack-1 [R=301,QSD]
RewriteRule ^pack-5$ /pack-5 [R=301,QSD]
RewriteRule ^pack-10$ /pack-10 [R=301,QSD]

The 3 rules above redirect to the address without parameters (dropped with the QSD flag, query string discard) only when the "colour=transparent" parameter is in the URL. This way, with a negation, you can run the sets of rules you need.

As I said, it is neither safe nor convenient. You have to know how many rules should count. So a simple mistake, such as a number that is too big, plants a time bomb. It will not throw a 500 error straight away; it will quietly switch off some rule further down. The same goes for removing or adding rules to such a "group" - you have to remember to update the [S] flag. It is worth marking such groups with clear comments before and after the set of rules.

A simpler alternative

If the rules in a group are similar, they can often be replaced by a single rule with a regular expression. Then one RewriteCond naturally applies to one RewriteRule, and the [S] flag is not needed:

RewriteCond %{QUERY_STRING} colour=transparent
RewriteRule ^pack-(1|5|10)$ /pack-$1 [R=301,QSD]

The brackets with bars (1|5|10) mean "one of these", and $1 puts whatever matched into the target address. Fewer lines, fewer places to make a mistake.

Advertisement