contains lots of theory on regular expressions as well. The Wikipedia page on regular expressions is great
for background information (
A regular expression (sometimes referred to as a
) is a special string that describes a text
With regular expressions you can define rules that match groups of strings, extract data from strings, and
transform strings, which enable very flexible and complex text manipulation using concise rules. Regular
expressions aren’t specific to mod_rewrite and URL rewriting. On the contrary, they’ve been around for a
while, and they’re implemented in many tools and programming languages, including PHP.
To demonstrate their usefulness with a simple example, assume your web site needs to rewrite links as
shown in Table 3-2.
If you have 100,000 products, without regular expressions you’d be in a bit of a trouble, because you’d
need to write just as many rules — no more, no less.
You don’t want to manage an
100,000 rewrite rules!
That would be unwieldy.
However, if you look at the Original URL column of the table, you’ll see that all entries follow the same
. And as suggested earlier, regular expressions can come to rescue! Patterns are useful because
with a single pattern you can match a theoretically infinite number of possible input URLs, so you just
need to write a rewriting rule for every
of URL you have in your web site.
In the exercise that follows, you use a regular expression that matches
, and use
mod_rewrite to translate URLs that match that pattern to
. This will
implement exactly the rules described in Table 3-1.
Working with Regular Expressions
file you created earlier in your
folder, and add the following
rewriting rule to it:
# Translate my-super.product.html to /product.php?product_id=123
RewriteRule ^my-super-product\.html$ /product.php?product_id=123
Chapter 3: Provocative SE-Friendly URLs
c03.qxd:c03 10:39 55